<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>Chapter 4: Appenders</title>
    <link rel="stylesheet" type="text/css" href="../css/site.css" />    
    <link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen"/>    
  </head>
  <body onload="prettyPrint(); decorate();">
    <script type="text/javascript">prefix='../';</script>
    <script type="text/javascript" src="../js/prettify.js"></script>
    <script type="text/javascript" src="../js/dsl.js"></script>
    <script type="text/javascript" src="../js/jquery-min.js"></script>
    <script type="text/javascript" src="../js/decorator.js"></script>

    <div id="container">
      <script type="text/javascript" src="../templates/header.js"></script>
      
      <div id="left">      
        <noscript>Please turn on Javascript to view this menu</noscript>
        <script src="../templates/left.js" type="text/javascript"></script>
      </div>    
      <div id="right">
        <script src="menu.js" type="text/javascript"></script>
      </div>

    <div id="content">

    <h1>Chapter 4: Appenders</h1>

    <div class="quote">

      <p><em>There is so much to tell about the Western country in
      that day that it is hard to know where to start. One thing sets
      off a hundred others. The problem is to decide which one to tell
      first.</em></p>
  
      <p>&mdash;JOHN STEINBECK, <em>East of Eden</em></p>
    </div>


    <script src="../templates/creative.js" type="text/javascript"></script>
    <script src="../templates/setup.js" type="text/javascript"></script>
    
    <h2 class="doAnchor" name="whatIsAnAppender">What is an Appender?</h2>
    
    <p>Logback delegates the task of writing a logging event to
      components called appenders.  Appenders must implement
      the <a href="../xref/ch/qos/logback/core/Appender.html"><code>ch.qos.logback.core.Appender</code></a>
      interface.  The salient methods of this interface are summarized
      below:
    </p>
    <div class="prettyprint source">package ch.qos.logback.core;
  
import ch.qos.logback.core.spi.ContextAware;
import ch.qos.logback.core.spi.FilterAttachable;
import ch.qos.logback.core.spi.LifeCycle;
  

public interface Appender&lt;E> extends LifeCycle, ContextAware, FilterAttachable {

  public String getName();
  public void setName(String name);
  <b>void doAppend(E event);</b>
  
}</div>

	<p>Most of the methods in the <code>Appender</code> interface are
	setters and getters. A notable exception is the
	<code>doAppend()</code> method taking an object instance of type
	<em>E</em> as its only parameter. The actual type of <em>E</em>
	will vary depending on the logback module. Within the
	logback-classic module <em>E</em> would be of type <a
	href="../apidocs/ch/qos/logback/classic/spi/ILoggingEvent.html">ILoggingEvent</a>
	and within the logback-access module it would be of type <a
	href="../apidocs/ch/qos/logback/access/spi/AccessEvent.html">AccessEvent</a>.
	The <code>doAppend()</code> method is perhaps the most important in
	the logback framework.  It is responsible for outputting the logging
	events in a suitable format to the appropriate output device.
  </p>

  <p>Appenders are named entities.  This ensures that they can be
  referenced by name, a quality confirmed to be instrumental in
  configuration scripts. The <code>Appender</code> interface extends
  the <code>FilterAttachable</code> interface. It follows that one or
  more filters can be attached to an appender instance. Filters are
  discussed in detail in a subsequent chapter.
	</p>
	
	<p>Appenders are ultimately responsible for outputting logging
	events.  However, they may delegate the actual formatting of the
	event to a <code>Layout</code> or to an <code>Encoder</code> object.
	Each layout/encoder is associated with one and only one appender,
	referred to as the owning appender. Some appenders have a built-in
	or fixed event format. Consequently, they do not require nor have a
	layout/encoder. For example, the <code>SocketAppender</code> simply
	serializes logging events before transmitting them over the wire.
	</p>
	
	
	<h2 class="doAnchor" name="AppenderBase">AppenderBase</h2>
	
	<p>The <a href="../xref/ch/qos/logback/core/AppenderBase.html">
	<code>ch.qos.logback.core.AppenderBase</code></a> class is an
	abstract class implementing the <code>Appender</code> interface.  It
	provides basic functionality shared by all appenders, such as
	methods for getting or setting their name, their activation status,
	their layout and their filters.  It is the super-class of all
	appenders shipped with logback.  Although an abstract class,
	<code>AppenderBase</code> actually implements the
	<code>doAppend()</code> method in the <code>Append</code> interface.
	Perhaps the clearest way to discuss <code>AppenderBase</code> class
	is by presenting an excerpt of actual source code.
	</p>
	
<pre class="prettyprint source">public synchronized void doAppend(E eventObject) {

  // prevent re-entry.
  if (guard) {
    return;
  }

  try {
    guard = true;

    if (!this.started) {
      if (statusRepeatCount++ &lt; ALLOWED_REPEATS) {
        addStatus(new WarnStatus(
            "Attempted to append to non started appender [" + name + "].",this));
      }
      return;
    }

    if (getFilterChainDecision(eventObject) == FilterReply.DENY) {
      return;
    }
    
    // ok, we now invoke the derived class's implementation of append
    this.append(eventObject);

  } finally {
    guard = false;
  }
}</pre>
	
	<p>This implementation of the <code>doAppend()</code> method is
	synchronized.  It follows that logging to the same appender from
	different threads is safe. While a thread, say <em>T</em>, is
	executing the <code>doAppend()</code> method, subsequent calls by
	other threads are queued until <em>T</em> leaves the
	<code>doAppend()</code> method, ensuring <em>T</em>'s exclusive
	access to the appender.
	</p>

  <p>Since such synchronization is not always appropriate, logback
  ships with <a
  href="../xref/ch/qos/logback/core/UnsynchronizedAppenderBase.html"><code>ch.qos.logback.core.UnsynchronizedAppenderBase</code></a>
  which is very similar to the <a
  href="../xref/ch/qos/logback/core/AppenderBase.html"><code>AppenderBase</code></a>
  class. For the sake of conciseness, we will be discussing
  <code>UnsynchronizedAppenderBase</code> in the remainder of this document.
  </p>


  <p>The first thing the <code>doAppend()</code> method does is to
  check whether the guard is set to true. If it is, it immediately
  exits. If the guard is not set, it is set to true at the next
  statement. The guard ensures that the <code>doAppend()</code> method
  will not recursively call itself. Just imagine that a component,
  called somewhere beyond the <code>append()</code> method, wants to
  log something. Its call could be directed to the very same appender
  that just called it resulting in an infinite loop and a stack
  overflow.
	</p>
	
	<p>In the following statement we check whether the
	<code>started</code> field is true.  If it is not,
	<code>doAppend()</code> will send a warning message and return.  In
	other words, once an appender is closed, it is impossible to write
	to it.  <code>Appender</code> objects implement the
	<code>LifeCycle</code> interface, which implies that they implement
	<code>start()</code>, <code>stop()</code> and
	<code>isStarted()</code> methods.  After setting all the properties of
	an appender, Joran, logback's configuration framework, calls the
	<code>start()</code> method to signal the appender to activate its
	properties.  Depending on its kind, an appender may fail to start if
	certain properties are missing or because of interference between
	various properties.  For example, given that file creation depends on
	truncation mode, <code>FileAppender</code> cannot act on the value
	of its <code>File</code> option until the value of the Append option
	is also known with certainty. The explicit activation step ensures
	that an appender acts on its properties <em>after</em> their values
	become known.
	</p>
	
	<p>If the appender could not be started or if it has been stopped, a
	warning message will be issued through logback's internal status
	management system. After several attempts, in order to avoid
	flooding the internal status system with copies of the same warning
	message, the <code>doAppend()</code> method will stop issuing these
	warnings.
  </p>

	<p>The next <code>if</code> statement checks the result of the
	attached filters.  Depending on the decision resulting from the
	filter chain, events can be denied or explicitly accepted.  In
	the absence of a decision by the filter chain, events are accepted
	by default.
	</p>
	
	<p>The <code>doAppend()</code> method then invokes the derived
	classes' implementation of the <code>append()</code> method. This
	method does the actual work of appending the event to the
	appropriate device.
	</p>
	
  <p>Finally, the guard is released so as to allow a subsequent
  invocation of the <code>doAppend()</code> method.
  </p>

	<p>For the remainder of this manual, we reserve the term "option" or
	alternatively "property" for any attribute that is inferred
	dynamically using JavaBeans introspection through setter and getter
	methods. </p>
	
	<h1>Logback-core</h1>
	
	<p>Logback-core lays the foundation upon which the other logback
	modules are built. In general, the components in logback-core
	require some, albeit minimal, customization. However, in the next
	few sections, we describe several appenders which are ready for use
	out of the box.
  </p>


	
	<h2 class="doAnchor"
	name="OutputStreamAppender">OutputStreamAppender
  </h2>
	
	<p><a
	href="../xref/ch/qos/logback/core/OutputStreamAppender.html"><code>OutputStreamAppender</code></a>
	appends events to a <code>java.io.OutputStream</code>.  This class
	provides basic services that other appenders build upon.  Users do
	not usually instantiate <code>OutputStreamAppender</code> objects
	directly, since in general the <code>java.io.OutputStream</code>
	type cannot be conveniently mapped to a string, as there is no way
	to specify the target <code>OutputStream</code> object in a
	configuration script.  Simply put, you cannot configure a
	<code>OutputStreamAppender</code> from a configuration file.
	However, this does not mean that <code>OutputStreamAppender</code>
	lacks configurable properties.  These properties are described next.
	</p>
	
  <table class="bodyTable striped">
    <tr>
      <th>Property Name</th>
      <th>Type</th>
      <th>Description</th>
    </tr>
    
    <tr>
      <td><span class="prop" name="osaEncoder">encoder</span></td>

      <td><a
      href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a></td>

      <td>Determines the manner in which an event is written to the
      underlying <code>OutputStreamAppender</code>. Encoders are
      described in a <a href="encoders.html">dedicated chapter</a>.
			</td>
    </tr>
   <tr>
     <td><span class="prop" name="immediateFlush">immediateFlush</span></td>
     <td><code>boolean</code></td>
     
     <td>The default value for <span
     class="option">immediateFlush</span> is 'true'. Immediate
     flushing of the output stream ensures that logging events are
     immediately written out and will not be lost in case your
     application exits without properly closing appenders. On the
     other hand, setting this property to 'false' is likely to
     quadruple (your mileage may vary) logging throughput. Again, if
     <span class="option">immediateFlush</span> is set to 'false' and
     if appenders are not closed properly when your application exits,
     then logging events not yet written to disk may be lost.
     </td>
    </tr>
	
	
	</table>
    
  <p>The <code>OutputStreamAppender</code> is the super-class of three other
	appenders, namely <code>ConsoleAppender</code>,
	<code>FileAppender</code> which in turn is the super class of
	<code>RollingFileAppender</code>. The next figure illustrates the
	class diagram for <code>OutputStreamAppender</code> and its subclasses.
	</p>
	
	<img src="images/chapters/appenders/appenderClassDiagram.jpg" alt="A UML diagram showing OutputStreamAppender and sub-classes"/>
	

	<h2 class="doAnchor" name="ConsoleAppender">ConsoleAppender</h2>
	
  <p>The <a href="../xref/ch/qos/logback/core/ConsoleAppender.html">
  <code>ConsoleAppender</code></a>, as the name indicates, appends on
  the console, or more precisely on <em>System.out</em> or
  <em>System.err</em>, the former being the default
  target. <code>ConsoleAppender</code> formats events with the help of
  an encoder specified by the user. Encoders will be discussed in a
  subsequent chapter. Both <em>System.out</em> and <em>System.err</em>
  are of type <code>java.io.PrintStream</code>.  Consequently, they
  are wrapped inside an <code>OutputStreamWriter</code> which buffers
  I/O operations.
	</p>
	
	<table class="bodyTable striped">
			<tr>
			<th>Property Name</th>
			<th>Type</th>
			<th>Description</th>
		</tr>
		<tr>
			<td><span class="prop" container="conApp">encoder</span></td>
      <td>
        <a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a>
      </td>
			<td>See <code>OutputStreamAppender</code> properties.</td>
		</tr>
		<tr>
			<td><span class="prop" container="conApp">target</span></td>
			<td><code>String</code></td>
			<td>
				One of the String values <em>System.out</em> or 
				<em>System.err</em>. The default target is <em>System.out</em>.
			</td>
		</tr>

		<tr>
			<td><span class="prop" container="conApp">withJansi</span></td>
			<td><code>boolean</code></td>
			<td>By the default <span class="prop">withJansi</span> property
			is set to <code>false</code>.  Setting <span
			class="prop">withJansi</span> to <code>true</code> activates the
			<a href="http://jansi.fusesource.org/">Jansi</a> library which
			provides support for ANSI color codes on Windows machines.  On a
			Windows host, if this property is set to true, then you should
			put "org.fusesource.jansi:jansi:${jansi.version}" on the class
			path. Note that Unix-based operating systems such as Linux and
			Mac OS X support ANSI color codes by default.

      <p>Under the Eclipse IDE, you might want to try the <a
      href="http://www.mihai-nita.net/eclipse/">ANSI in Eclipse
      Console</a> plugin.
      </p>
			</td>
		</tr>

	</table>
	
	<p>Here is a sample configuration that uses
	<code>ConsoleAppender</code>.
	</p>



  <p class="example">Example: ConsoleAppender configuration
  (logback-examples/src/main/resources/chapters/appenders/conf/logback-Console.xml)</p>

  <pre id="logback_Console" class="prettyprint source">&lt;configuration>

  <b>&lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    &lt;!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    &lt;encoder>
      &lt;pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender></b>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="STDOUT" />
  &lt;/root>
&lt;/configuration></pre>

   <p>After you have set your current path to the
   <em>logback-examples</em> directory and <a href="../setup.html">set
   up your class path</a>, you can give the above configuration file a
   whirl by issuing the following command:
	 </p>

   <p class="source">java <a
   href="../xref/chapters/appenders/ConfigurationTester.html">chapters.appenders.ConfigurationTester</a> src/main/java/chapters/appenders/conf/logback-Console.xml</p>
	
	
   <h2 class="doAnchor" name="FileAppender">FileAppender</h2>
	
   <p>The <a
   href="../xref/ch/qos/logback/core/FileAppender.html"><code>FileAppender</code></a>,
   a subclass of <code>OutputStreamAppender</code>, appends log events into
   a file. The target file is specified by the <span
   class="prop">File</span> option.  If the file already exists, it
   is either appended to, or truncated depending on the value of the
   <span class="prop">append</span> property.   
   </p>
	
   <table class="bodyTable properties striped">
     <tr>
       <th>Property Name</th>
       <th>Type</th>
       <th>Description</th>
     </tr>
     <tr>
       <td><span class="prop" container="fileApppender">append</span></td>
       <td><code>boolean</code></td>
       <td>If true, events are appended at the end of an existing
       file.  Otherwise, if <span class="prop">append</span> is false,
       any existing file is truncated. The <span
       class="option">append</span> option is set to true by default.
       </td>
     </tr>
     <tr >
       <td><span class="prop" container="fileApppender">encoder</span></td>
       <td>
         <a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a>
       </td>
       <td>See <code>OutputStreamAppender</code> properties.</td>
     </tr>
    
   
     <tr>
       <td><span class="prop"
       container="fileApppender">file</span></td>
       <td><code>String</code></td>
       <td>The name of the file to write to. If the file does not
       exist, it is created. On the MS Windows platform users
       frequently forget to escape back slashes.  For example, the
       value <em>c:\temp\test.log</em> is not likely to be interpreted
       properly as <em>'\t'</em> is an escape sequence interpreted as
       a single tab character <em>(\u0009)</em>.  Correct values can
       be specified as <em>c:/temp/test.log</em> or alternatively as
       <em>c:\\temp\\test.log</em>.  The <span
       class="prop">File</span> option has no default value.

       <p>If the parent directory of the file does not exist,
       <code>FileAppender</code> will automatically create it,
       including any necessary but nonexistent parent directories.
       </p>
       </td>
     </tr>

     <tr>
       <td><span class="prop" name="prudent">prudent</span></td>
       <td><code>boolean</code></td>

       <td>In prudent mode, <code>FileAppender</code> will safely
         write to the specified file, even in the presence of other
         <code>FileAppender</code> instances running in different
         JVMs, potentially running on different hosts. The default
         value for prudent mode is <code>false</code>.

         <p>Prudent mode can be used in conjunction with
         <code>RollingFileAppender</code> although some <a
         href="#prudentWithRolling">restrictions apply</a>.</p>

         <p>Prudent mode implies that <span
         class="prop">append</span> property is automatically set to
         true.
         </p>

         <p>Prudent more relies on exclusive file locks. Experiments
         show that file locks approximately triple (x3) the cost of
         writing a logging event. On an "average" PC writing to a file
         located on a <b>local</b> hard disk, when prudent mode is
         off, it takes about 10 microseconds to write a single logging
         event. When prudent mode is on, it takes approximately 30
         microseconds to output a single logging event. This
         translates to logging throughput of 100'000 events per second
         when prudent mode is off and approximately 33'000 events per
         second in prudent mode.
         </p>

         <p>Prudent mode effectively serializes I/O operations between
         all JVMs writing to the same file. Thus, as the number of
         JVMs competing to access a file increases so will the delay
         incurred by each I/O operation. As long as the <em>total</em>
         number of I/O operations is in the order of 20 log requests
         per second, the impact on performance should be
         negligible. Applications generating 100 or more I/O
         operations per second can see an impact on performance and
         should avoid using <span class="prop">prudent</span> mode.
         </p>

         <p><span class="label">Networked file locks</span> When the
         log file is located on a networked file system, the cost of
         prudent mode is even greater. Just as importantly, file locks
         over a networked file system can be sometimes strongly biased
         such that the process currently owning the lock immediately
         re-obtains the lock upon its release. Thus, while one process
         hogs the lock for the log file, other processes starve
         waiting for the lock to the point of appearing deadlocked.
         </p>
         
         <p>The impact of prudent mode is highly dependent on network
         speed as well as the OS implementation details. We provide an
         very small application called <a
         href="https://gist.github.com/2794241">FileLockSimulator</a>
         which can help you simulate the behavior of prudent mode in
         your environment.
         </p>


       </td>
       
     </tr>
   </table>
	
   <p><span class="label notice">Immediate Flush</span> By default,
   each log event is immediately flushed to the underlying output
   stream. This default approach is safer in the sense that logging
   events are not lost in case your application exits without properly
   closing appenders. However, for significantly increased logging
   throughput, you may want to set the <span
   class="prop">immediateFlush</span> property to
   <code>false</code>.</p>

   <p>Below is an example of a configuration file for
   <code>FileAppender</code>:
	 </p>

   <p class="example">Example: FileAppender configuration
   (logback-examples/src/main/resources/chapters/appenders/conf/logback-fileAppender.xml)</p>

   <pre id="logback-fileAppender"  class="prettyprint source">&lt;configuration>

  <b>&lt;appender name="FILE" class="ch.qos.logback.core.FileAppender">
    &lt;file>testFile.log&lt;/file>
    &lt;append>true&lt;/append>
    &lt;!-- set immediateFlush to false for much higher logging throughput -->
    &lt;immediateFlush>true&lt;/immediateFlush>
    &lt;!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    &lt;encoder>
      &lt;pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender></b>
	
  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration></pre>

   <p>After changing the current directory to
   <em>logback-examples</em>, run this example by launching the
   following command:
   </p>
	
   <p class="source">java chapters.appenders.ConfigurationTester
   src/main/java/chapters/appenders/conf/logback-fileAppender.xml</p>
	
	
   <h3 class="doAnchor" name="uniquelyNamed">Uniquely named files (by
   timestamp)</h3>
   
   <p>During the application development phase or in the case of
   short-lived applications, e.g. batch applications, it is desirable
   to create a new log file at each new application launch. This is
   fairly easy to do with the help of the <code>&lt;timestamp></code>
   element. Here's an example.</p>


   <p class="example">Example: Uniquely named FileAppender
   configuration by timestamp
   (logback-examples/src/main/resources/chapters/appenders/conf/logback-timestamp.xml)</p>

   <pre id="logback-timestamp" class="prettyprint source">&lt;configuration>

  &lt;!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under
       the key "bySecond" into the logger context. This value will be
       available to all subsequent configuration elements. -->
  <b>&lt;timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/></b>

  &lt;appender name="FILE" class="ch.qos.logback.core.FileAppender">
    &lt;!-- use the previously created timestamp to create a uniquely
         named log file -->
    &lt;file><b>log-${bySecond}.txt</b>&lt;/file>
    &lt;encoder>
      &lt;pattern>%logger{35} - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration></pre>


   <p>The timestamp element takes two mandatory attributes <span
   class="attr">key</span> and <span class="attr">datePattern</span>
   and an optional <span class="attr">timeReference</span>
   attribute. The <span class="attr">key</span> attribute is the name
   of the key under which the timestamp will be available to
   subsequent configuration elements <a
   href="configuration.html#variableSubstitution">as a
   variable</a>. The <span class="attr">datePattern</span> attribute
   denotes the date pattern used to convert the current time (at which
   the configuration file is parsed) into a string. The date pattern
   should follow the conventions defined in <a
   href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>. The
   <span class="attr">timeReference</span> attribute denotes the time
   reference for the time stamp. The default is the
   interpretation/parsing time of the configuration file, i.e. the
   current time. However, under certain circumstances it might be
   useful to use the context birth time as time reference. This can be
   accomplished by setting the <span class="attr">timeReference</span>
   attribute to <code>"contextBirth"</code>.
   </p>

   <p>Experiment with the <code>&lt;timestamp></code> element by
   running the command:</p>

   <p class="command">java chapters.appenders.ConfigurationTester src/main/resources/chapters/appenders/conf/logback-timestamp.xml</p>

   <p>To use the logger context birth date as time reference, you
   would set the <span class="attr">timeReference</span> attribute to
   "contextBirth" as shown below.</p>


   <p class="example">Example: Timestamp using context birth date as time reference
   (logback-examples/src/main/resources/chapters/appenders/conf/logback-timestamp-contextBirth.xml)</p>

   <pre id="logback-timestamp-contextBirth" class="prettyprint source">&lt;configuration>
  &lt;timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss" 
             <b>timeReference="contextBirth"</b>/>
  ...
&lt;/configuration></pre>

   <h2 class="doAnchor" name="RollingFileAppender">RollingFileAppender
   </h2>
   
   <p><a
	 href="../xref/ch/qos/logback/core/rolling/RollingFileAppender.html"><code>RollingFileAppender</code></a>
	 extends <code>FileAppender</code> with the capability to rollover log
	 files.  For example, <code>RollingFileAppender</code> can log to a
	 file named <em>log.txt</em> file and, once a certain condition is
	 met, change its logging target to another file.
   </p>
     
   <p>There are two important sub-components that interact with
   <code>RollingFileAppender</code>. The first
   <code>RollingFileAppender</code> sub-component, namely
   <code>RollingPolicy</code>, (<a href="#onRollingPolicies">see
   below</a>) is responsible for undertaking the actions required for
   a rollover. A second sub-component of
   <code>RollingFileAppender</code>, namely
   <code>TriggeringPolicy</code>, (<a href="#TriggeringPolicy">see
   below</a>) will determine if and exactly when rollover
   occurs. Thus, <code>RollingPolicy</code> is responsible for the
   <em>what</em> and <code>TriggeringPolicy</code> is responsible for
   the <em>when</em>. </p>
	
   <p>To be of any use, a <code>RollingFileAppender</code> must have
   both a <code>RollingPolicy</code> and a
   <code>TriggeringPolicy</code> set up. However, if its
   <code>RollingPolicy</code> also implements the
   <code>TriggeringPolicy</code> interface, then only the former needs
   to be specified explicitly.
   </p>
	
   <p>Here are the available properties for <code>RollingFileAppender</code>:</p>
	
   <table class="bodyTable striped">
     <tr>
       <th>Property Name</th>
       <th>Type</th>
       <th>Description</th>
     </tr>
     <tr>
       <td><span class="prop" container="rfa">file</span></td>
       <td><code>String</code></td>
       <td>See <code>FileAppender</code> properties.</td>
     </tr>	
     <tr>
       <td><span class="prop" container="rfa">append</span></td>
       <td><code>boolean</code></td>
       <td>See <code>FileAppender</code> properties.</td>
     </tr>	
     <tr>
       <td><span class="prop" container="rfa">encoder</span></td>
       <td>
         <a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a>
       </td>
       <td>See <code>OutputStreamAppender</code> properties.</td>
     </tr>
     <tr>
       <td><span class="prop" container="rfa">rollingPolicy</span></td>
       <td><code>RollingPolicy</code></td>
       <td>This option is the component that will dictate
       <code>RollingFileAppender</code>'s behavior when rollover
       occurs. See more information below.
       </td>
     </tr>	
     <tr>
       <td><span class="prop" container="rfa">triggeringPolicy</span></td>
       <td><code>TriggeringPolicy</code></td>
       <td>
         This option is the component that will tell 
         <code>RollingFileAppender</code> when to activate the rollover
         procedure. See more information below.
       </td>
     </tr>	
     <tr>
       <td valign="top"><span class="prop" name="prudentWithRolling">prudent</span></td>

       <td valign="top"><code>boolean</code></td>

       <td  valign="top">
         <a
         href="#FixedWindowRollingPolicy"><code>FixedWindowRollingPolicy</code></a>
         is not supported in prudent mode.

         <p> <code>RollingFileAppender</code> supports the prudent
         mode in conjunction with <a
         href="#TimeBasedRollingPolicy"><code>TimeBasedRollingPolicy</code></a>
         albeit with two restrictions.
         </p>

         <ol>
           <li>In prudent mode, file compression is not supported nor
           allowed. (We can't have one JVM writing to a file while
           another JVM is compressing it.)  </li>
           
           <li>The <span class="prop">file</span> property of
           <code>FileAppender</code> cannot be set and must be left
           blank. Indeed, most operating systems do not allow renaming
           of a file while another process has it opened.
           </li>
           
         </ol>

         See also properties for <code>FileAppender</code>.
       </td>
     </tr>
   </table>
	
   <h3 class="doAnchor" name="onRollingPolicies">Overview of rolling
   policies</h3>
	
   <p><a
   href="../xref/ch/qos/logback/core/rolling/RollingPolicy.html"><code>RollingPolicy</code></a>
   is responsible for the rollover procedure which involves file
   moving and renaming.</p>
	
   <p>The <code>RollingPolicy</code> interface is presented below:</p>
   
   <pre class="prettyprint source">package ch.qos.logback.core.rolling;  

import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.spi.LifeCycle;

public interface RollingPolicy extends LifeCycle {

  <b>public void rollover() throws RolloverFailure;</b>
  public String getActiveFileName();
  public CompressionMode getCompressionMode();
  public void setParent(FileAppender appender);
}</pre>

   <p>The <code>rollover</code> method accomplishes the work involved
   in archiving the current log file.  The
   <code>getActiveFileName()</code> method is called to compute the
   file name of the current log file (where live logs are written
   to). As indicated by <code>getCompressionMode</code> method a
   RollingPolicy is also responsible for determining the compression
   mode. Lastly, a <code>RollingPolicy</code> is given a reference to
   its parent via the <code>setParent</code> method.
   </p>

   <!-- =================
        ================= -->

	
   <h4 class="doAnchor" name="TimeBasedRollingPolicy">TimeBasedRollingPolicy </h4>

   <p><a
   href="../xref/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.html">
   <code>TimeBasedRollingPolicy</code></a> is possibly the most
   popular rolling policy. It defines a rollover policy based on time,
   for example by day or by month.
   <code>TimeBasedRollingPolicy</code> assumes the responsibility for
   rollover as well as for the triggering of said rollover. Indeed,
   <code>TimeBasedTriggeringPolicy</code> implements <em>both</em>
   <code>RollingPolicy</code> and <code>TriggeringPolicy</code>
   interfaces.
   </p>

   <p><code>TimeBasedRollingPolicy</code>'s configuration takes one
   mandatory <span class="prop">fileNamePattern</span> property and
   several optional properties.
   </p>

   <table class="bodyTable striped">
     <tr>
       <th>Property Name</th>
       <th>Type</th>
       <th>Description</th>
     </tr>
     <tr>
       <td><span class="prop" container="tbrp">fileNamePattern</span></td>
       <td><code>String</code></td>
       <td>
         The mandatory <span class="prop">fileNamePattern</span>
         property defines the name of the rolled-over (archived) log
         files. Its value should consist of the name of the file, plus
         a suitably placed <em>%d</em> conversion specifier.  The
         <em>%d</em> conversion specifier may contain a date-and-time
         pattern as specified by the
         <code>java.text.SimpleDateFormat</code> class.  If the
         date-and-time pattern is omitted, then the default pattern
         <em>yyyy-MM-dd</em> is assumed. <b>The rollover period is
         inferred from the value of <span
         class="prop">fileNamePattern</span>.</b>


         <p>Note that the <span class="prop">file</span> property in
         <code>RollingFileAppender</code> (the parent of
         <code>TimeBasedRollingPolicy</code>) can be either set or
         omitted. By setting the <span class="prop">file</span>
         property of the containing <code>FileAppender</code>, you can
         decouple the location of the active log file and the location
         of the archived log files. The current logs will be always
         targeted at the file specified by the <span
         class="prop">file</span> property. It follows that the name
         of the currently active log file will not change over
         time. However, if you choose to omit the <span
         class="prop">file</span> property, then the active file
         will be computed anew for each period based on the value of
         <span class="prop">fileNamePattern</span>.  The examples
         below should clarify this point.
         </p>

         <p>The date-and-time pattern, as found within the accolades
         of %d{} follow java.text.SimpleDateFormat conventions. The
         forward slash '/' or backward slash '\' characters anywhere
         within the <span class="option">fileNamePattern</span>
         property or within the date-and-time pattern will be
         interpreted as directory separators.
         </p>

         <h5>Multiple %d specifiers</h5> 

         <p>It is possible to specify multiple %d specifiers but only
         one of which can be primary, i.e. used to infer the rollover
         period. All other tokens <em>must</em> be marked as auxiliary
         by passing the 'aux' parameter (see examples below).</p>
         
         <p>Multiple %d specifiers allow you to organize archive files
         in a folder structure different than that of the roll-over
         period. For example, the file name pattern shown below
         organizes log folders by year and month but roll-over log
         files every day at midnight.</p>
         
         <pre>/var/log/<b>%d{yyyy/MM, aux}</b>/myapplication.<b>%d{yyyy-MM-dd}</b>.log</pre>

         <h5>TimeZone</h5> 

         <p>Under certain circumstances, you might wish to roll-over
         log files according to a clock in a timezone different than
         that of the host. It is possible to pass a timezone argument
         following the date-and-time pattern within the %d conversion
         specifier. For example:</p>

         <pre>aFolder/test.<b>%d</b>{yyyy-MM-dd-HH, <b>UTC</b>}.log</pre>

         <p>If the specified timezone identifier is unknown or
         misspelled, the GMT timezone is assumed as dictated by the <a
         href="http://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getTimeZone(java.lang.String)">TimeZone.getTimeZone(String)</a>
         method specification.
         </p>
       </td>
     </tr>
     <tr>
       <td><span class="prop" container="tbrp">maxHistory</span></td>
       <td>int</td>
       <td>The optional <span class="prop">maxHistory</span> property
       controls the maximum number of archive files to keep,
       asynchronously deleting older files. For example, if you
       specify monthly rollover, and set maxHistory to 6, then 6
       months worth of archives files will be kept with files older
       than 6 months deleted. Note as old archived log files are
       removed, any folders which were created for the purpose of log
       file archiving will be removed as appropriate.
       </td>
     </tr>

     <tr>
       <td><span class="prop" container="tbrp">totalSizeCap</span></td>
       <td>int</td>
       <td><p>The optional <span class="prop">totalSizeCap</span>
       property controls the total size of all archive files. Oldest
       archives are deleted asynchronously when the total size cap is
       exceeded. The <span class="prop">totalSizeCap</span> property
       requires <span class="option">maxHistory</span> property to be
       set as well.  Moreover, the "max history" restriction is always
       applied first and the "total size cap" restriction applied
       second. </p>
       </td>
     </tr>

     <tr >
       <td><span class="prop"
       container="tbrp">cleanHistoryOnStart</span></td>
       <td>boolean</td>
       <td>
         <p>If set to true, archive removal will be executed on
         appender start up. By default this property is set to
         false. </p>

         <p>Archive removal is normally performed during roll
         over. However, some applications may not live long enough for
         roll over to be triggered. It follows that for such
         short-lived applications archive removal may never get a
         chance to execute.  By setting <span
         class="prop">cleanHistoryOnStart</span> to true, archive
         removal is performed at appender start up.</p>
       </td>
     </tr>
   </table>


   <p>Here are a few <code>fileNamePattern</code> values with an
   explanation of their effects.</p>

  
   
   <table class="bodyTable striped">
     <tr>
       <th>
         <span class="prop">fileNamePattern</span>
       </th>
       <th>Rollover schedule</th>
       <th>Example</th>
     </tr>
     <tr>
       <td class="small">
         <em>/wombat/foo.%d</em>
       </td>
       <td>Daily rollover (at midnight). Due to the omission of the
       optional time and date pattern for the <em>%d</em> token
       specifier, the default pattern of <em>yyyy-MM-dd</em> is
       assumed, which corresponds to daily rollover.
       </td>

       <td>
         <p><span class="prop">file</span> property not set: During November
         23rd, 2006, logging output will go to the file
         <em>/wombat/foo.2006-11-23</em>.  At midnight and for the
         rest of the 24th, logging output will be directed to
         <em>/wombat/foo.2006-11-24</em>.
       </p>

         <p><span class="prop">file</span> property set to
         <em>/wombat/foo.txt</em>: During November 23rd, 2006, logging
         output will go to the file <em>/wombat/foo.txt</em>. At
         midnight, <em>foo.txt</em> will be renamed as
         <em>/wombat/foo.2006-11-23</em>. A new
         <em>/wombat/foo.txt</em> file will be created and for the
         rest of November 24th logging output will be directed to
         <em>foo.txt</em>.
       </p>

       </td>
     </tr>
     

     <tr>
       <td class="small">
         <em>/wombat/%d{yyyy/MM}/foo.txt</em>
       </td>
       <td>Rollover at the beginning of each month.</td>
       <td>
         <p><span class="prop">file</span> property not set: During
         the month of October 2006, logging output will go to
         <em>/wombat/2006/10/foo.txt</em>.  After midnight of October
         31st and for the rest of November, logging output will be
         directed to <em>/wombat/2006/11/foo.txt</em>.
         </p>

         <p><span class="prop">file</span> property set to
         <em>/wombat/foo.txt</em>: The active log file will always be
         <em>/wombat/foo.txt</em>. During the month of October 2006,
         logging output will go to <em>/wombat/foo.txt</em>. At
         midnight of October 31st, <em>/wombat/foo.txt</em> will be
         renamed as <em>/wombat/2006/10/foo.txt</em>. A new
         <em>/wombat/foo.txt</em> file will be created where logging
         output will go for the rest of November. At midnight of
         November 30th, <em>/wombat/foo.txt</em> will be renamed as
         <em>/wombat/2006/11/foo.txt</em> and so on.
         </p>
       </td>
     </tr>
     <tr>
       <td class="small">
         <em>/wombat/foo.%d{yyyy-ww}.log</em>
       </td>
       
       <td>Rollover at the first day of each week. Note that the first
       day of the week depends on the locale.</td>
       
       <td>Similar to previous cases, except that rollover will occur
       at the beginning of every new week.  
       </td>     
     </tr>	
     <tr>
       <td class="small">
         <em>/wombat/foo%d{yyyy-MM-dd_HH}.log</em>
       </td>
       <td>Rollover at the top of each hour.</td>
       <td>Similar to previous cases, except that rollover will occur
       at the top of every hour.
       </td>
     </tr>
     <tr>
       <td class="small">
         <em>/wombat/foo%d{yyyy-MM-dd_HH-mm}.log</em>
       </td>
       <td>Rollover at the beginning of every minute.</td>
       <td>Similar to previous cases, except that rollover will occur
       at the beginning of every minute.  
       </td>     
     </tr>
     <tr>
       <td class="small">
         <em>/wombat/foo%d{yyyy-MM-dd_HH-mm, UTC}.log</em>
       </td>
       <td>Rollover at the beginning of every minute.</td>
       <td>Similar to previous cases, except that file names will be
       expressed in UTC.
       </td>     
     </tr>


     <tr>
       <td class="small">
         <em>/foo/%d{yyyy-MM,<b>aux</b>}/%d.log</em>
       </td>
       <td>Rollover daily. Archives located under a folder containing
       year and month.
       </td>
       <td>In this example, the first %d token is marked as
       <b>aux</b>iliary. The second %d token, with time and date
       pattern omitted, is then assumed to be primary. Thus, rollover
       will occur daily (default for %d) and the folder name will
       depend on the year and month. For example, during the month of
       November 2006, archived files will all placed under the
       /foo/2006-11/ folder, e.g <em>/foo/2006-11/2006-11-14.log</em>.
       </td>     
       
     </tr>
   </table>
   
   <p>Any forward or backward slash characters are interpreted as
   folder (directory) separators. Any required folder will be created
   as necessary. You can thus easily place your log files in separate
   folders.
   </p>


 	 <p><code>TimeBasedRollingPolicy</code> supports automatic file
 	 compression.  This feature is enabled if the value of the <span
 	 class="prop">fileNamePattern</span> option ends with <em>.gz</em>
 	 or <em>.zip</em>.
   </p>

   <table class="bodyTable striped">
     <tr class="a">
       <th><span class="prop">fileNamePattern</span></th>
       <th>Rollover schedule</th>
       <th>Example</th>
     </tr>
     <tr>
       <td><em>/wombat/foo.%d.gz</em></td>
       <td>Daily rollover (at midnight) with automatic GZIP compression of the 
       archived files.</td>
       <td>
         <p><span class="prop">file</span> property not set: During
         November 23rd, 2009, logging output will go to the file
         <em>/wombat/foo.2009-11-23</em>. However, at midnight that
         file will be compressed to become
         <em>/wombat/foo.2009-11-23.gz</em>.  For the 24th of November,
         logging output will be directed to
         <em>/wombat/folder/foo.2009-11-24</em> until it's rolled over
         at the beginning of the next day.
         </p>
         
         <p><span class="prop">file</span> property set to
         /wombat/foo.txt: During November 23rd, 2009, logging output
         will go to the file <em>/wombat/foo.txt</em>. At midnight that
         file will be compressed and renamed as
         <em>/wombat/foo.2009-11-23.gz</em>.  A new
         <em>/wombat/foo.txt</em> file will be created where logging
         output will go for the rest of November 24rd. At midnight
         November 24th, <em>/wombat/foo.txt</em> will be compressed and
         renamed as <em>/wombat/foo.2009-11-24.gz</em> and so on.
         </p>
       </td>
     </tr>
   </table>
   
   <p>The <span class="prop">fileNamePattern</span> serves a dual
   purpose. First, by studying the pattern, logback computes the
   requested rollover periodicity. Second, it computes each archived
   file's name. Note that it is possible for two different patterns to
   specify the same periodicity. The patterns <em>yyyy-MM</em> and
   <em>yyyy@MM</em> both specify monthly rollover, although the
   resulting archive files will carry different names.
   </p>

	 <p>By setting the <span class="prop">file</span> property you can
	 decouple the location of the active log file and the location of
	 the archived log files. The logging output will be targeted into
	 the file specified by the <span class="prop">file</span>
	 property. It follows that the name of the active log file will not
	 change over time. However, if you choose to omit the <span
	 class="prop">file</span> property, then the active file will be
	 computed anew for each period based on the value of <span
	 class="prop">fileNamePattern</span>. By leaving the <span
	 class="prop">file</span> option unset you can avoid file <a
	 href="../codes.html#renamingError">renaming errors</a> which occur
	 while there exist external file handles referencing log files during
	 roll over.
   </p>
	
   <p>The <span class="prop">maxHistory</span> property controls the
   maximum number of archive files to keep, deleting older files. For
   example, if you specify monthly rollover, and set <span
   class="prop">maxHistory</span> to 6, then 6 months worth of
   archives files will be kept with files older than 6 months
   deleted. Note as old archived log files are removed, any folders
   which were created for the purpose of log file archiving will be
   removed as appropriate.
   </p>

   <p>For various technical reasons, rollovers are not clock-driven
   but depend on the arrival of logging events. For example, on 8th of
   March 2002, assuming the <span
   class="prop">fileNamePattern</span> is set to <em>yyyy-MM-dd</em>
   (daily rollover), the arrival of the first event after midnight
   will trigger a rollover. If there are no logging events during, say
   23 minutes and 47 seconds after midnight, then rollover will
   actually occur at 00:23'47 AM on March 9th and not at 0:00 AM.
   Thus, depending on the arrival rate of events, rollovers might be
   triggered with some latency.  However, regardless of the delay, the
   rollover algorithm is known to be correct, in the sense that all
   logging events generated during a certain period will be output in
   the correct file delimiting that period.
   </p>
	
   <p>Here is a sample configuration for
   <code>RollingFileAppender</code> in conjunction with a
   <code>TimeBasedRollingPolicy</code>.
   </p>
	
   <p class="example">Example: Sample configuration of a
   <code>RollingFileAppender</code> using a
   <code>TimeBasedRollingPolicy</code>
   (logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingTimeBased.xml)</p>

   <pre id="logback-RollingTimeBased" class="prettyprint source">&lt;configuration>
  &lt;appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    &lt;file>logFile.log&lt;/file>
    <b>&lt;rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      &lt;!-- daily rollover -->
      &lt;fileNamePattern>logFile.%d{yyyy-MM-dd}.log&lt;/fileNamePattern>

      &lt;!-- keep 30 days' worth of history capped at 3GB total size -->
      &lt;maxHistory>30&lt;/maxHistory>
      &lt;totalSizeCap>3GB&lt;/totalSizeCap>

    &lt;/rollingPolicy></b>

    &lt;encoder>
      &lt;pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender> 

  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration></pre>

    <p>The next configuration sample illustrates the use of
    <code>RollingFileAppender</code> associated with
    <code>TimeBasedRollingPolicy</code> in <span class="prop">prudent</span>
    mode.
    </p>

   <p class="example">Example: Sample configuration of a
   <code>RollingFileAppender</code> using a
   <code>TimeBasedRollingPolicy</code>
   (logback-examples/src/main/resources/chapters/appenders/conf/logback-PrudentTimeBasedRolling.xml)</p>

  <pre id="logback-PrudentTimeBasedRolling" class="prettyprint source">&lt;configuration>
  &lt;appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <b>&lt;!-- Support multiple-JVM writing to the same log file --></b>
    <b>&lt;prudent>true&lt;/prudent></b>
    &lt;rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      &lt;fileNamePattern>logFile.%d{yyyy-MM-dd}.log&lt;/fileNamePattern>
      &lt;maxHistory>30&lt;/maxHistory> 
      &lt;totalSizeCap>3GB&lt;/totalSizeCap>
    &lt;/rollingPolicy>

    &lt;encoder>
      &lt;pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender> 

  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration></pre>

  

    <h3 class="doAnchor" name="SizeAndTimeBasedRollingPolicy">Size and
    time based rolling policy</h3>

    
     <p>Sometimes you may wish to archive files essentially by date but
    at the same time limit the size of each log file, in particular if
    post-processing tools impose size limits on the log files. In
    order to address this requirement, logback ships with
    <code>SizeAndTimeBasedRollingPolicy</code>.</p>

    <p>Note that <code>TimeBasedRollingPolicy</code> already allows
    limiting the combined size of archived log files. If you only wish
    to limit the combined size of log archives, then
    <code>TimeBasedRollingPolicy</code> described above and setting
    the <a href="#tbrpTotalSizeCap"><span
    class="option">totalSizeCap</span></a> property should be amply
    sufficent.
    </p>

    <p>Here is a sample configuration file demonstrating time and size
    based log file archiving.</p>
    
  <p class="example">Example: Sample configuration for
  <code>SizeAndTimeBasedFNATP</code> 
  (logback-examples/src/main/resources/chapters/appenders/conf/logback-sizeAndTime.xml)</p>

  <pre id="logback-sizeAndTime" class="prettyprint source">&lt;configuration>
  &lt;appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    &lt;file>mylog.txt&lt;/file>
    &lt;rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      &lt;!-- rollover daily -->
      &lt;fileNamePattern><b>mylog-%d{yyyy-MM-dd}.<span class="big">%i</span>.txt</b>&lt;/fileNamePattern>
       <b>&lt;!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB --></b>
       <b>&lt;maxFileSize>100MB&lt;/maxFileSize></b>    
       &lt;maxHistory>60&lt;/maxHistory>
       &lt;totalSizeCap>20GB&lt;/totalSizeCap>
    &lt;/rollingPolicy>
    &lt;encoder>
      &lt;pattern>%msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>


  &lt;root level="DEBUG">
    &lt;appender-ref ref="ROLLING" />
  &lt;/root>

&lt;/configuration></pre>
    
    <p>Note the "%i" conversion token in addition to "%d". <b>Both the
    %i and %d tokens are mandatory.</b> Each time the current log file
    reaches <span class="prop">maxFileSize</span> before the current
    time period ends, it will be archived with an increasing index,
    starting at 0.</p>

    <p>Size and time based archiving supports deletion of old archive
    files. You need to specify the number of periods to preserve with
    the <span class="prop">maxHistory</span> property. When your
    application is stopped and restarted, logging will continue at the
    correct location, i.e. at the largest index number for the current
    period.
    </p>

    <p>In versions prior to 1.1.7, this document mentioned a component
    called <code>SizeAndTimeBasedFNATP</code>. However, given that
    <code>SizeAndTimeBasedFNATP</code> offers a simpler configuration
    structure, we no longer document
    <code>SizeAndTimeBasedFNATP</code>.  Nevertheless, earlier
    configuration files using <code>SizeAndTimeBasedFNATP</code> will
    continue to work just fine. In fact,
    <code>SizeAndTimeBasedRollingPolicy</code> is implemented with a
    <code>SizeAndTimeBasedFNATP</code> subcomponent.</p>

   <h4 class="doAnchor" name="FixedWindowRollingPolicy">FixedWindowRollingPolicy</h4>

   <p>When rolling over, <a
   href="../xref/ch/qos/logback/core/rolling/FixedWindowRollingPolicy.html">
   <code>FixedWindowRollingPolicy</code></a> renames files according
   to a fixed window algorithm as described below.
   </p>

   <p>The <span class="prop">fileNamePattern</span> option
   represents the file name pattern for the archived (rolled over) log
   files.  This option is required and must include an integer token
   <em>%i</em> somewhere within the pattern.
   </p>
	
   <p>Here are the available properties for
   <code>FixedWindowRollingPolicy</code>
   </p>
	
   <table class="bodyTable striped">
     <tr>
       <th>Property Name</th>
       <th>Type</th>
       <th>Description</th>
     </tr>
     <tr>
       <td><span class="prop" container="fwrp">minIndex</span></td>
       <td><code>int</code></td>
       <td>
         <p>This option represents the lower bound for the window's
         index.
         </p>
       </td>
     </tr>
     <tr>
       <td><span class="prop" container="fwrp">maxIndex</span></td>
       <td><code>int</code></td>
       <td>
         <p>This option represents the upper bound for the window's
         index.
         </p>
       </td>
     </tr>
     <tr>
       <td><span class="prop" container="fwrp">fileNamePattern</span></td>
       <td><code>String</code></td>
       <td>
         <p>This option represents the pattern that will be followed
         by the <code>FixedWindowRollingPolicy</code> when renaming
         the log files. It must contain the string <em>%i</em>, which
         will indicate the position where the value of the current
         window index will be inserted.
         </p>
         <p>For example, using <em>MyLogFile%i.log</em> associated
         with minimum and maximum values of <em>1</em> and <em>3</em>
         will produce archive files named <em>MyLogFile1.log</em>,
         <em>MyLogFile2.log</em> and <em>MyLogFile3.log</em>.
         </p>
         <p>Note that file compression is also specified via this
         property. For example, <span
         class="prop">fileNamePattern</span> set to
         <em>MyLogFile%i.log.zip</em> means that archived files must be
         compressed using the <em>zip</em> format; <em>gz</em> format
         is also supported.
         </p>
       </td>
     </tr>			
   </table>
   
   <p>Given that the fixed window rolling policy requires as many file
   renaming operations as the window size, large window sizes are
   strongly discouraged. When large values are specified by the user,
   the current implementation will automatically reduce the window
   size to 20.
   </p>

   <p>Let us go over a more concrete example of the fixed window
   rollover policy. Suppose that <span class="prop">minIndex</span> is
   set to <em>1</em>, <span class="prop">maxIndex</span> set to
   <em>3</em>, <span class="prop">fileNamePattern</span> property set
   to <em>foo%i.log</em>, and that <span class="prop">file</span>
   property is set to <em>foo.log</em>.
   </p>
	
   <table class="bodyTable striped">
     <tr>
       <th>Number of rollovers</th>
       <th>Active output target</th>
       <th>Archived log files</th>
       <th>Description</th>
     </tr>
		<tr>
			<td>0</td>
			<td>foo.log</td>
			<td>-</td>
			<td>No rollover has happened yet, logback logs into the initial
			file.
			</td>
     </tr>		
     <tr>
       <td>1</td>
       <td>foo.log</td>
       <td>foo1.log</td>
       <td>First rollover. <em>foo.log</em> is renamed as
       <em>foo1.log</em>. A new <em>foo.log</em> file is created and
       becomes the active output target.
       </td>
     </tr>
     <tr>
       <td>2</td>
       <td>foo.log</td>
       <td>foo1.log, foo2.log</td>
       <td>Second rollover. <em>foo1.log</em> is renamed as
       <em>foo2.log</em>.  <em>foo.log</em> is renamed as
       <em>foo1.log</em>. A new <em>foo.log</em> file is created and
       becomes the active output target.
       </td>
     </tr>
     <tr>
       <td>3</td>
       <td>foo.log</td>
       <td>foo1.log, foo2.log, foo3.log</td>
       <td>Third rollover.  <em>foo2.log</em> is renamed as
       <em>foo3.log</em>. <em>foo1.log</em> is renamed as
       <em>foo2.log</em>.  <em>foo.log</em> is renamed as
       <em>foo1.log</em>. A new <em>foo.log</em> file is created and
       becomes the active output target.
       </td>
     </tr>
     <tr>
       <td>4</td>
       <td>foo.log</td>
       <td>foo1.log, foo2.log, foo3.log</td>
       <td>In this and subsequent rounds, the rollover begins by
       deleting <em>foo3.log</em>. Other files are renamed by
       incrementing their index as shown in previous steps. In this and
       subsequent rollovers, there will be three archive logs and one
       active log file.
       </td>
     </tr>
   </table>
	
   <p>The configuration file below gives an example of configuring
   <code>RollingFileAppender</code> and
   <code>FixedWindowRollingPolicy</code>. Note that the <span
   class="prop">File</span> option is mandatory even if it contains
   some of the same information as conveyed with the <span
   class="prop">fileNamePattern</span> option.
   </p>
	
   <p class="example">Example: Sample configuration of a <code>RollingFileAppender</code> using a 
   <code>FixedWindowRollingPolicy</code> (logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingFixedWindow.xml)</p>

   <pre id="logback-RollingFixedWindow" class="prettyprint source">&lt;configuration>
  &lt;appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <b>&lt;file>test.log&lt;/file></b>

    <b>&lt;rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      &lt;fileNamePattern>tests.%i.log.zip&lt;/fileNamePattern>
      &lt;minIndex>1&lt;/minIndex>
      &lt;maxIndex>3&lt;/maxIndex>
    &lt;/rollingPolicy></b>

    &lt;triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      &lt;maxFileSize>5MB&lt;/maxFileSize>
    &lt;/triggeringPolicy>
    &lt;encoder>
      &lt;pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>
	
  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration></pre>


		<h2>
      <a name="TriggeringPolicy" href="#TriggeringPolicy">Overview of
      triggering policies</a>
    </h2>
		
		<p><a
		href="../xref/ch/qos/logback/core/rolling/TriggeringPolicy.html"><code>TriggeringPolicy</code></a>
		implementations are responsible for instructing the
		<code>RollingFileAppender</code> when to rollover.</p>
		
		<p>The <code>TriggeringPolicy</code> interface contains only one
		method.</p>
	
    <pre class="prettyprint source">package ch.qos.logback.core.rolling;

import java.io.File;
import ch.qos.logback.core.spi.LifeCycle;

public interface TriggeringPolicy&lt;E&gt; extends LifeCycle {

  <b>public boolean isTriggeringEvent(final File activeFile, final &lt;E&gt; event);</b>
}</pre>

		<p>The <code>isTriggeringEvent()</code> method takes as parameters
		the active file and the logging event currently being
		processed. The concrete implementation determines whether the
		rollover should occur or not, based on these parameters.
		</p>

    <p>The most widely-used triggering policy, namely
    <code>TimeBasedRollingPolicy</code> which also doubles as a
    rolling policy, was already <a
    href="#TimeBasedRollingPolicy">discussed earlier</a> along with
    other rolling policies. </p>
		
		<h4><a name="SizeBasedTriggeringPolicy"
		href="#SizeBasedTriggeringPolicy">SizeBasedTriggeringPolicy</a></h4>

		<p><a
		href="../xref/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicy.html">
		<code>SizeBasedTriggeringPolicy</code></a> looks at the size of the
		currently active file. If it grows larger than the specified size,
		it will signal the owning <code>RollingFileAppender</code> to
		trigger the rollover of the existing active file.
		</p>

		<p><code>SizeBasedTriggeringPolicy</code> accepts only one
		parameter, namely <span class="prop">maxFileSize</span>, with a
		default value of 10 MB.
		</p>

		<p>The <span class="prop">maxFileSize</span> option can be
		specified in bytes, kilobytes, megabytes or gigabytes by suffixing
		a numeric value with <em>KB</em>, <em>MB</em> and respectively
		<em>GB</em>. For example, <em>5000000</em>, <em>5000KB</em>,
		<em>5MB</em> and <em>2GB</em> are all valid values, with the first
		three being equivalent.
		</p>

		<p>Here is a sample configuration with a
		<code>RollingFileAppender</code> in conjunction with
		<code>SizeBasedTriggeringPolicy</code> triggering rollover when
		the log file reaches 5MB in size.
		</p>

    <p class="example">Example: Sample configuration of a
    <code>RollingFileAppender</code> using a
    <code>SizeBasedTriggeringPolicy</code>
    (logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingSizeBased.xml)</p>

    <pre id="logback-RollingSizeBased" class="prettyprint source">&lt;configuration>
  &lt;appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    &lt;file>test.log&lt;/file>
    &lt;rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      &lt;fileNamePattern>test.%i.log.zip&lt;/fileNamePattern>
      &lt;minIndex>1&lt;/minIndex>
      &lt;maxIndex>3&lt;/maxIndex>
    &lt;/rollingPolicy>

    <b>&lt;triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
      &lt;maxFileSize>5MB&lt;/maxFileSize>
    &lt;/triggeringPolicy></b>
    &lt;encoder>
      &lt;pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>
	
  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration></pre>

	
    <!-- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx -->
		<a name="Classic"></a>
		<h2>Logback Classic</h2>
				
    
		<p>While logging events are generic in logback-core, within
		logback-classic they are always instances of
		<code>ILoggingEvent</code>. Logback-classic is nothing more than a
		specialized processing pipeline handling instances of
		<code>ILoggingEvent</code>.

    </p>

		<h3 class="doAnchor" name="SocketAppender">SocketAppender and
		SSLSocketAppender
    </h3>
		
		<p>The appenders covered thus far are only able to log to local
		resources.  In contrast, the <a
		href="../xref/ch/qos/logback/classic/net/SocketAppender.html">
		<code>SocketAppender</code></a> is designed to log to a remote
		entity by transmitting serialized <code>ILoggingEvent</code>
		instances over the wire.  When using <code>SocketAppender</code>
		logging events on the wire are sent in the clear.  However, when
		using  <a href="../xref/ch/qos/logback/classic/net/SSLSocketAppender.html">
		<code>SSLSocketAppender</code></a>, logging events are delivered over
		a secure channel.</p>

    <p>
		The actual type of the serialized event
		is <a
		href="../xref/ch/qos/logback/classic/spi/LoggingEventVO.html"><code>LoggingEventVO</code></a>
		which implements the <code>ILoggingEvent</code>
		interface. Nevertheless, remote logging is non-intrusive as far as
		the logging event is concerned.  On the receiving end after
		deserialization, the event can be logged as if it were generated
		locally. Multiple <code>SocketAppender</code> instances running on
		different machines can direct their logging output to a central
		log server whose format is fixed.  <code>SocketAppender</code>
		does not take an associated layout because it sends serialized
		events to a remote server.  <code>SocketAppender</code> operates
		above the <em>Transmission Control Protocol (TCP)</em> layer which
		provides a reliable, sequenced, flow-controlled end-to-end octet
		stream.  Consequently, if the remote server is reachable, then log
		events will eventually arrive there. Otherwise, if the remote
		server is down or unreachable, the logging events will simply be
		dropped. If and when the server comes back up, then event
		transmission will be resumed transparently.  This transparent
		reconnection is performed by a connector thread which periodically
		attempts to connect to the server.
		</p>
		
		<p>Logging events are automatically buffered by the native TCP
		implementation.  This means that if the link to server is slow but
		still faster than the rate of event production by the client, the
		client will not be affected by the slow network
		connection. However, if the network connection is slower than the
		rate of event production, then the client can only progress at the
		network rate. In particular, in the extreme case where the network
		link to the server is down, the client will be eventually blocked.
		Alternatively, if the network link is up, but the server is down,
		the client will not be blocked, although the log events will be
		lost due to server unavailability.
		</p>
		
		<p>Even if a <code>SocketAppender</code> is no longer attached to
		any logger, it will not be garbage collected in the presence of a
		connector thread.  A connector thread exists only if the
		connection to the server is down.  To avoid this garbage
		collection problem, you should close the
		<code>SocketAppender</code> explicitly. Long lived applications
		which create/destroy many <code>SocketAppender</code> instances
		should be aware of this garbage collection problem. Most other
		applications can safely ignore it.  If the JVM hosting the
		<code>SocketAppender</code> exits before the
		<code>SocketAppender</code> is closed, either explicitly or
		subsequent to garbage collection, then there might be
		untransmitted data in the pipe which may be lost. This is a common
		problem on Windows based systems.  To avoid lost data, it is
		usually sufficient to <code>close()</code> the
		<code>SocketAppender</code> either explicitly or by calling the
		<code>LoggerContext</code>'s <code>stop()</code>
		method before exiting the application.
		</p>
		
		<p>The remote server is identified by the <span
		class="prop">remoteHost</span> and <span
		class="prop">port</span> properties.
		<code>SocketAppender</code> properties are listed in the following
		table.  <code>SSLSocketAppender</code> supports many additional
		configuration properties, which are detailed in the section 
		entitled <a href="usingSSL.html">Using SSL</a>.
		</p>

    <table class="bodyTable striped">
      <tr>
			<th>Property Name</th>
			<th>Type</th>
			<th>Description</th>
      </tr>
      <tr>
        <td><span class="prop" container="socket">includeCallerData</span></td>
        <td><code>boolean</code></td>
        <td>
          <p>
            The <span class="prop" container="socket">includeCallerData</span> option takes a boolean value. 
            If true, the caller data will be available to the remote host. 
            By default no caller data is sent to the server.
          </p>
        </td>
      </tr>
      <tr>
        <td><span class="prop" container="socket">port</span></td>
        <td><code>int</code></td>
        <td>
          <p>
            The port number of the remote server.
          </p>
        </td>
      </tr>	
      <tr>
        <td><span class="prop"
        container="socket">reconnectionDelay</span></td>
        <td><code><a
        href="../apidocs/ch/qos/logback/core/util/Duration.html">Duration</a></code></td>
        <td>
          The <span class="prop">reconnectionDelay</span> option takes
          a duration string, such "10 seconds" representing the time
          to wait between each failed connection attempt to the
          server.  The default value of this option is 30 seconds.
          Setting this option to zero turns off reconnection
          capability.  Note that in case of successful connection to
          the server, there will be no connector thread present.
        </td>
      </tr>
      <tr>
        <td><span class="prop" container="socket">queueSize</span></td>
        <td><code>int</code></td>
        <td>
          <p>The <span class="prop">queueSize</span> property takes an
          integer (greater than zero) representing the number of logging
          events to retain for delivery to the remote receiver.  When
          the queue size is one, event delivery to the remote
          receiver is synchronous.  When the queue size is greater
          than one, new events are enqueued, assuming that there is
          space available in the queue. Using a queue length greater
          than one can improve performance by eliminating delays caused
          by transient network delays.
          </p>

          <p>See also the <span class="prop">eventDelayLimit</span>
          property.</p>

        </td>
      </tr>	

      <tr>
        <td><span class="prop" container="socket">eventDelayLimit</span></td>
        <td><code><a
        href="../apidocs/ch/qos/logback/core/util/Duration.html">Duration</a></code></td>
        <td>
          The <span class="prop">eventDelayLimit</span> option takes a
          duration string, such "10 seconds". It represents the time
          to wait before dropping events in case the local queue is
          full, i.e. already contains <span
          class="prop">queueSize</span> events.  This may occur if the
          remote host is persistently slow accepting events. The
          default value of this option is 100 milliseconds.
        </td>
      </tr>
      <tr>
        <td><span class="prop" container="socket">remoteHost</span></td>
        <td><code>String</code></td>
        <td>
          The host name of the server.
        </td>
      </tr>		
      <tr>
        <td><span class="prop" container="socket">ssl</span></td>
        <td><code>SSLConfiguration</code></td>
        <td>Supported only for <code>SSLSocketAppender</code>, this
            property provides the SSL configuration that will be used by
            the appender, as described in <a href="usingSSL.html">Using SSL</a>.
        </td>
      </tr>
    </table>
    
    <h4>Logging Server Options</h4>
    <p>The standard Logback Classic distribution includes two options
    for servers that can be used to receive logging events from
    <code>SocketAppender</code> or <code>SSLSocketAppender</code>.</p>
    <ul>
      <li><code>ServerSocketReceiver</code> and its SSL-enabled 
      counterpart <code>SSLServerSocketReceiver</code> are receiver
      components which can be configured in the <em>logback.xml</em> 
      configuration file of an application in order receive events
      from a remote socket appender.  See <a href="receivers.html">
      Receivers</a> for configuration details and usage examples.
      </li>
      <li><code>SimpleSocketServer</code> and its SSL-enabled counterpart
      <code>SimpleSSLSocketServer</code> both offer an 
      easy-to-use standalone Java application that is designed to
      be configured and run from your shell's command line interface.
      These applications simply wait for logging events from 
      <code>SocketAppender</code> or <code>SSLSocketAppender</code>
      clients.  Each received event is logged according to local server 
      policy.  Usage examples are given below.
      </li>
    </ul>
    
    <h4><a name="simpleSocketServer"></a>Using SimpleSocketServer</h4>
    <p>
    The <code>SimpleSocketServer</code> application takes two command-line
    arguments: <em>port</em> and <em>configFile</em>; 
    where <em>port</em> is the port to listen on and
    <em>configFile</em> is a configuration script in XML format.
    </p>
	
    <p>
      Assuming you are in the <em>logback-examples/</em> directory, 
      start <code>SimpleSocketServer</code> with the following command:
    </p>
    
    <p class="source">java ch.qos.logback.classic.net.SimpleSocketServer 6000 \
  src/main/java/chapters/appenders/socket/server1.xml</p>

    <p>where 6000 is the port number to listen on and
    <em>server1.xml</em> is a configuration script that adds a
    <code>ConsoleAppender</code> and a
    <code>RollingFileAppender</code> to the root logger.  After you
    have started <code>SimpleSocketServer</code>, you can send it log
    events from multiple clients using <code>SocketAppender</code>.
    The examples associated with this manual include two such clients:
    <code>chapters.appenders.SocketClient1</code> and
    <code>chapters.appenders.SocketClient2</code> Both clients wait for the user
    to type a line of text on the console.  The text is encapsulated
    in a logging event of level debug and then sent to the remote
    server. The two clients differ in the configuration of the
    <code>SocketAppender</code>. <code>SocketClient1</code> configures
    the appender programmatically while <code>SocketClient2</code>
    requires a configuration file.
    </p>
	
    <p>Assuming <code>SimpleSocketServer</code> is running on the
    local host, you connect to it with the following command:
    </p>
	
    <p class="source">java chapters.appenders.socket.SocketClient1 localhost 6000</p>

		<p>Each line that you type should appear on the console of the
		<code>SimpleSocketServer</code> launched in the previous step. If
		you stop and restart the <code>SimpleSocketServer</code> the
		client will transparently reconnect to the new server instance,
		although the events generated while disconnected will be simply
		(and irrevocably) lost.
		</p>

		<p>
			Unlike
			<code>SocketClient1</code>, the sample application
			<code>SocketClient2</code> does not configure logback by itself. 
			It requires a configuration file in XML format. 
			The configuration file <em>client1.xml</em>
			shown below creates a <code>SocketAppender</code>
			and attaches it to the root logger.
		</p>

		<p class="example">Example: SocketAppender configuration
		(logback-examples/src/main/resources/chapters/appenders/socket/client1.xml)</p>

<pre id="client1" class="prettyprint source">&lt;configuration>
	  
  &lt;appender name="SOCKET" class="ch.qos.logback.classic.net.SocketAppender">
    &lt;remoteHost>${host}&lt;/remoteHost>
    &lt;port>${port}&lt;/port>
    &lt;reconnectionDelay>10000&lt;/reconnectionDelay>
    &lt;includeCallerData>${includeCallerData}&lt;/includeCallerData>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="SOCKET" />
  &lt;/root>  

&lt;/configuration></pre>
	
		<p>
			Note that in the above configuration scripts the values for the 
			<span class="prop">remoteHost</span>, <span class="prop">port</span> and
			<span class="prop">includeCallerData</span> properties
			are not given directly but as substituted variable keys. The values for the variables 
			can be specified as system properties: 
		</p>
	
    <p class="source">java -Dhost=localhost -Dport=6000 -DincludeCallerData=false \
  chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/client1.xml</p>

		<p>This command should give similar results to the previous
			<code>SocketClient1</code>
			example.
		</p>
		
		<p>Allow us to repeat for emphasis that serialization of logging
		events is not intrusive. A deserialized event carries the same
		information as any other logging event. It can be manipulated as
		if it were generated locally; except that serialized logging
		events by default do not include caller data. Here is an example
		to illustrate the point. First, start
		<code>SimpleSocketServer</code> with the following command:
		</p>

    <p class="source"> java ch.qos.logback.classic.net.SimpleSocketServer 6000 \
  src/main/java/chapters/appenders/socket/server2.xml</p>

   <p>The configuration file <em>server2.xml</em> creates a
   <code>ConsoleAppender</code> whose layout outputs the caller's file
   name and line number along with other information. If you run
   <code>SocketClient2</code> with the configuration file
   <em>client1.xml</em> as previously, you will notice that the output
   on the server side will contain two question marks between
   parentheses instead of the file name and the line number of the
   caller:
		</p>

    <p class="source">2006-11-06 17:37:30,968 DEBUG [Thread-0] [?:?] chapters.appenders.socket.SocketClient2 - Hi</p>

		<p>The outcome can be easily changed by instructing the
		<code>SocketAppender</code> to include caller data by setting the
		<span class="prop">includeCallerData</span> option to
		true. Using the following command will do the trick:
		</p>

   <pre class="source">java -Dhost=localhost -Dport=6000 -DincludeCallerData=true \
  chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/client1.xml</pre>

		<p>As deserialized events can be handled in the same way as
		locally generated events, they even can be sent to a second server
		for further treatment.  As an exercise, you may wish to setup two
		servers where the first server tunnels the events it receives from
		its clients to a second server.
		</p>
		
		<h4><a name="simpleSSLSocketServer"></a>Using SimpleSSLSocketServer</h4>

    <p>The <code>SimpleSSLSocketServer</code> requires the same
    <em>port</em> and <em>configFile</em> command-line arguments used
    by <code>SimpleSocketServer</code>.  Additionally, you must provide
    the location and password for your logging server's X.509 credential
    using system properties specified on the command line.
    </p>
    
    <p>Assuming you are in the <em>logback-examples/</em> directory, 
    start <code>SimpleSSLSocketServer</code> with the following command:
    </p>

    <p class="source">java -Djavax.net.ssl.keyStore=src/main/java/chapters/appenders/socket/ssl/keystore.jks \
    -Djavax.net.ssl.keyStorePassword=changeit \
    ch.qos.logback.classic.net.SimpleSSLSocketServer 6000 \
    src/main/java/chapters/appenders/socket/ssl/server.xml
    </p>
	
    <p>This example runs <code>SimpleSSLSocketServer</code> using an
    X.509 credential that is suitable for testing and experimentation, 
    only.  <strong>Before using <code>SimpleSSLSocketServer</code> in a
    production setting you should obtain an appropriate X.509 credential
    to identify your logging server</strong>.  See 
    <a href="usingSSL.html">Using SSL</a> for more details.
    </p>
    
    <p>Because the server configuration has <code>debug="true"</code>
    specified on the root element, you'll will see in the server's
    startup logging the SSL configuration that will be used.  This is
    useful in validating that local security policies are properly
    implemented.
    </p>

    <p>With <code>SimpleSSLSocketServer</code> running, you can connect
    to the server using an <code>SSLSocketAppender</code>.  The following
    example shows the appender configuration needed:
    </p>
      
   	<p class="example">Example: SSLSocketAppender configuration
		(logback-examples/src/main/resources/chapters/appenders/socket/ssl/client.xml)</p>

<pre id="sslclient" class="prettyprint source">&lt;configuration debug="true">
	  
  &lt;appender name="SOCKET" class="ch.qos.logback.classic.net.SSLSocketAppender">
    &lt;remoteHost>${host}&lt;/remoteHost>
    &lt;port>${port}&lt;/port>
    &lt;reconnectionDelay>10000&lt;/reconnectionDelay>
    &lt;ssl>
      &lt;trustStore>
        &lt;location>${truststore}&lt;/location>
        &lt;password>${password}&lt;/password>
      &lt;/trustStore>
    &lt;/ssl>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="SOCKET" />
  &lt;/root>  

&lt;/configuration></pre>
	  
	  <p>Note that, just as in the previous example, the values for
	  <span class="prop">remoteHost</span>, <span class="prop">port</span>
	  are specified using substituted variable keys.  Additionally, note
	  the presence of the <span class="prop">ssl</span> property and its
	  nested <span class="prop">trustStore</span> property, which specifies
	  the location and password of a trust store using substituted
	  variables.  This configuration is necessary because our example
	  server is using a self-signed certificate.  See 
	  <a href="usingSSL.html">Using SSL</a> for more information on 
	  SSL configuration properties for <code>SSLSocketAppender</code>.
	  </p>

    <p>We can run a client application using this configuration by
    specifying the substitution variable values on the command line as
    system properties:
    </p>
    	  	
    <p class="source">java -Dhost=localhost -Dport=6000 \
    -Dtruststore=file:src/main/java/chapters/appenders/socket/ssl/truststore.jks \
    -Dpassword=changeit \
    chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/ssl/client.xml
 	  </p>
 	  
 	  <p>As in the previous examples, you can type in a message when 
 	  prompted by the client application, and the message will be delivered
 	  to the logging server (now over a secure channel) where it will be
 	  displayed on the console.
 	  </p>
 	  
 	  <p>Note that the <em>truststore</em> property given on the command
 	  line specifies a file URL that identifies the location of the
 	  trust store.  You may also use a classpath URL as described in <a
 	  href="usingSSL.html">Using SSL</a>.
 	  </p>
 
    <p>As we saw previously at server startup, because the client
    configuration has <code>debug="true"</code> specified on the root
    element, the client's startup logging includes the details of the
    SSL configuration as aid to auditing local policy conformance.
    </p>
 	  
 	  
    <h3 class="doAnchor" name="serverSocketAppender">
      ServerSocketAppender and SSLServerSocketAppender</h3>
    
    <p>The <code>SocketAppender</code> component (and its SSL-enabled
    counterpart) discussed previously are designed to allow an
    application to connect to a remote logging server over the network
    for the purpose of delivering logging events to the server.  In
    some situations, it may be inconvenient or infeasible to have an
    application initiate a connection to a remote logging server.  For
    these situations, Logback offers <a
    href="../xref/ch/qos/logback/classic/net/server/ServerSocketAppender">
    <code>ServerSocketAppender</code></a>.
    </p>
    
    <p>Instead of initiating a connection to a remote logging server, 
    <code>ServerSocketAppender</code> passively listens on a TCP socket
    awaiting incoming connections from remote clients.  Logging events
    that are delivered to the appender are distributed to each connected
    client.  Logging events that occur when no client is connected are
    <em>summarily discarded</em>.
    </p>
    
    <p>In addition to the basic <code>ServerSocketAppender</code>, Logback
    offers <a href="../xref/ch/qos/logback/classic/net/server/SSLServerSocketAppender">
    <code>SSLServerSocketAppender</code></a>, which distributes logging events
    to each connected client using a secure, encrypted channel.  Moreover, the
    SSL-enabled appender fully supports mutual certificate-based authentication,
    which can be used to ensure that only authorized clients can connect to
    the appender to receive logging events.   
    </p>
   
    <p>The approach to encoding logging events for transmission on the wire 
    is identical to that used by <code>SocketAppender</code>; each event is 
    a serialized instance of <code>ILoggingEvent</code>.  Only the direction 
    of connection initiation is reversed.  While <code>SocketAppender</code> 
    acts as the active peer in establishing the connection to a logging server,
    <code>ServerSocketAppender</code> is passive; it listens for
    incoming connections from clients.</p>  

    <p>The <code>ServerSocketAppender</code> subtypes are intended to be
    used exclusively with Logback <em>receiver</em> components.  See
    <a href="receivers.html">Receivers</a> for additional information on
    this component type.</p>
    
    <p>The following configuration properties are supported by 
    <code>ServerSocketAppender</code>:</p>
    
    <table class="bodyTable striped">
      <tr>
      <th>Property Name</th>
      <th>Type</th>
      <th>Description</th>
      </tr>
      <tr>
        <td><span class="prop" container="serverSocketAppender">address</span></td>
        <td><code>String</code></td>
        <td>The local network interface address on which the appender
        will listen.  If this property is not specified, the appender
        will listen on all network interfaces.</td>
      </tr>
      <tr>
        <td><span class="prop" container="serverSocketAppender">includeCallerData</span></td>
        <td><code>boolean</code></td>
        <td>
          <p>
            If true, the caller data will be available to the remote host. 
            By default no caller data is sent to the client.
          </p>
        </td>
      </tr>
      <tr>
        <td><span class="prop" container="serverSocketAppender">port</span></td>
        <td><code>int</code></td>
        <td>
          <p>
            The port number on which the appender will listen.
          </p>
        </td>
      </tr> 
      <tr>
        <td><span class="prop" container="serverSocketAppender">ssl</span></td>
        <td><code>SSLConfiguration</code></td>
        <td>Supported only for <code>SSLServerSocketAppender</code>, this
            property provides the SSL configuration that will be used by
            the appender, as described in <a href="usingSSL.html">Using SSL</a>.
        </td>
      </tr>
    </table>
    
    <p>The following example illustrates a configuration that uses
      <code>ServerSocketAppender</code>:
    </p>

    <p class="example">Example: Basic ServerSocketAppender Configuration
    (logback-examples/src/main/resources/chapters/appenders/socket/server4.xml)</p>
<pre id="SocketReceiver" class="prettyprint source">&lt;configuration debug="true">
  &lt;appender name="SERVER" 
    class="ch.qos.logback.classic.net.server.ServerSocketAppender">
    &lt;port>${port}&lt;/port>
    &lt;includeCallerData>${includeCallerData}&lt;/includeCallerData>
  &lt;/appender>

  &lt;root level="debug">
    &lt;appender-ref ref="SERVER" />
  &lt;/root>  

&lt;/configuration>
</pre>
    <p>Note that this configuration differs from previous examples using
    <code>SocketAppender</code> only in the <em>class</em> specified for
    the appender, and in the absence of the <span class="prop">remoteHost</span>
    property &mdash; this appender waits passively for inbound connections 
    from remote hosts rather than opening a connection to a remote logging
    server.
    </p>
    
    <p>The following example illustrates a configuration using
    <code>SSLServerSocketAppender</code>.</p>
        
     <p class="example">Example: Basic SSLServerSocketAppender Configuration
    (logback-examples/src/main/resources/chapters/appenders/socket/ssl/server3.xml)</p>
<pre id="SocketReceiver" class="prettyprint source">&lt;configuration debug="true">
  &lt;appender name="SERVER" 
    class="ch.qos.logback.classic.net.server.SSLServerSocketAppender">
    &lt;port>${port}&lt;/port>
    &lt;includeCallerData>${includeCallerData}&lt;/includeCallerData>
    &lt;ssl>
      &lt;keyStore>
        &lt;location>${keystore}&lt;/location>
        &lt;password>${password}&lt;/password>
      &lt;/keyStore>
    &lt;/ssl>
  &lt;/appender>

  &lt;root level="debug">
    &lt;appender-ref ref="SERVER" />
  &lt;/root>  

&lt;/configuration>
</pre>
   
    <p>The principal differences between this configuration and the
    previous configuration is that the appender's <em>class</em> attribute
    identifies the <code>SSLServerSocketAppender</code> type, and the
    presence of the nested <span class="prop">ssl</span> element which
    specifies, in this example, configuration of a key store containing
    an X.509 credential for the appender.  See <a href="usingSSL.html">
    Using SSL</a> for information regarding SSL configuration properties.
    </p>
    
    <p>Because the <code>ServerSocketAppender</code> subtypes are designed
    to be used with receiver components, we will defer presenting 
    illustrative examples to the chapter entitled 
    <a href="receivers.html">Receivers</a>.</p>
    
   <h3 class="doAnchor">SMTPAppender</h3>
   
   <p>The <a
   href="../xref/ch/qos/logback/classic/net/SMTPAppender.html"><code>SMTPAppender</code></a>
   accumulates logging events in one or more fixed-size buffers and
   sends the contents of the appropriate buffer in an email after a
   user-specified event occurs.  SMTP email transmission (sending) is
   performed asynchronously. By default, the email transmission is
   triggered by a logging event of level ERROR. Moreover, by default,
   a single buffer is used for all events.
   </p>
		
   <p>The various properties for <code>SMTPAppender</code> are
   summarized in the following table.
	 </p>
		
		<table class="bodyTable striped">
      <tr>
        <th>Property Name</th>
        <th>Type</th>
        <th>Description</th>
      </tr>

      <tr>
        <td><span class="prop" container="smtp">smtpHost</span></td>
        <td><code>String</code></td>
        <td>The host name of the SMTP server. This parameter is mandatory.</td>
      </tr>
      
      <tr>
        <td><span class="prop" container="smtp">smtpPort</span></td>
        <td><code>int</code></td>
        <td>The port where the SMTP server is listening. Defaults to
        25.</td>
      </tr>
      
      <tr>
        <td><span class="prop" name="smtpTo">to</span></td>
        <td><code>String</code></td>
        <td>The email address of the recipient as a
        <em>pattern</em>. The pattern is evaluated anew with the
        triggering event as input for each outgoing email. Multiple
        recipients can be specified by separating the destination
        addresses with commas.  Alternatively, multiple recipients can
        also be specified by using multiple <code>&lt;to></code>
        elements. 
        </td>
      </tr>

      <tr>
        <td><span class="prop" container="smtp">from</span></td>
        <td><code>String</code></td>
        <td>The originator of the email messages sent by
        <code>SMTPAppender</code> in the <a
        href="http://en.wikipedia.org/wiki/Email_address">usual email
        address format</a>. If you wish to include the sender's name,
        then use the format
        "Adam&nbsp;Smith&nbsp;&amp;lt;smith@moral.org&amp;gt;" so that
        the message appears as originating from
        "Adam&nbsp;Smith&nbsp;&lt;smith@moral.org&gt;".
        </td>
      </tr>
      <tr>
        <td><span class="prop">subject</span></td>
        <td><code>String</code></td>
        <td> 
          <p>The subject of the email. It can be any value accepted as
          a valid conversion pattern by <a
          href="layouts.html#ClassicPatternLayout">PatternLayout</a>. Layouts
          will be discussed in the next chapter.
          </p>
          
          <p>The outgoing email message will have a subject line
          corresponding to applying the pattern on the logging event
          that triggered the email message.
          </p>

          <p>Assuming the <span class="prop">subject</span> option
          is set to "Log: %logger - %msg" and the triggering event's
          logger is named "com.foo.Bar", and contains the message
          "Hello world", then the outgoing email will have the subject
          line "Log: com.foo.Bar - Hello World".
          </p>

          <p>By default, this option is set to "%logger{20} - %m".</p>
        </td>
        
      </tr>
      <tr>
        <td><span class="prop" container="smtp">discriminator</span></td>
        <td><code><a href="../xref/ch/qos/logback/core/sift/Discriminator.html">Discriminator</a></code></td>
        <td>
          <p>With the help of a <span
          class="prop">Discriminator</span>,
          <code>SMTPAppender</code> can scatter incoming events into
          different buffers according to the value returned by the
          discriminator. The default discriminator always returns the
          same value so that the same buffer is used for all events.
          </p>

          <p>By specifying a discriminator other than the default
          one, it is possible to receive email messages
          containing a events pertaining to a particular user, user
          session or client IP address.
          </p>
        </td>
      </tr>
      <tr>
        <td><span class="prop" name="smtpAppender_Evaluator">evaluator</span></td>
        <td><code><a
        href="../xref/ch/qos/logback/classic/boolex/IEvaluator.html">IEvaluator</a></code></td>
        <td>
          <p>This option is declared by creating a new
          <code>&lt;EventEvaluator/></code> element. The name of the
          class that the user wishes to use as the
          <code>SMTPAppender</code>'s <code>Evaluator</code> needs
          to be specified via the <span class="attr">class</span>
          attribute.
          </p>
          
          
          <p>In the absence of this option, <code>SMTPAppender</code>
          is assigned an instance of <a
          href="../xref/ch/qos/logback/classic/boolex/OnErrorEvaluator.html">OnErrorEvaluator</a>
          which triggers email transmission when it encounters an
          event of level <em>ERROR</em> or higher.
          </p>

          <!--
          <p><code>EventEvaluator</code> objects are subclasses of the
          <code>JaninoEventEvaluatorBase</code> which depends on
          Janino. See the <a href="../dependencies.html">dependencies
          page</a> for more information.
          </p>
          -->

          <p>Logback ships with several other evaluators, namely <a
          href="../xref/ch/qos/logback/classic/boolex/OnMarkerEvaluator.html"><code>OnMarkerEvaluator</code></a>
          (discussed below) and a powerful evaluator called <a
          href="../xref/ch/qos/logback/classic/boolex/JaninoEventEvaluator.html"><code>JaninoEventEvaluator</code></a>,
          discussed in <a href="filters.html#evalutatorFilter">another
          chapter</a>. The more recent versions of logback ship with
          an even more powerful evaluator called <a
          href="filters.html#GEventEvaluator"><code>GEventEvaluator</code></a>.
          </p>

        </td>
      </tr>

      <tr>
        <td  valign="top"><span class="prop" container="smtp">cyclicBufferTracker</span></td>
        <td><a href="../xref/ch/qos/logback/core/spi/CyclicBufferTracker.html"><code>CyclicBufferTracker</code></a>
        </td>
        <td>
          <p>As the name indicates, an instance of the
          <code>CyclicBufferTracker</code> class tracks cyclic
          buffers. It does so based on the keys returned by the <span
          class="prop">discriminator</span> (see above).
          </p>
          <p>If you don't specify a <span
          class="prop">cyclicBufferTracker</span>, an instance of <a
          href="../xref/ch/qos/logback/core/spi/CyclicBufferTracker.html">CyclicBufferTracker</a>
          will be automatically created. By default, this instance
          will keep events in a cyclic buffer of size 256. You may
          change the size with the help of the <span
          class="prop">bufferSize</span> option (see below).</p>
        </td>        
      </tr>
      <tr>
        <td><span class="prop" container="smtp">username</span></td>
        <td><code>String</code></td> <td>The username value to use
        during plain user/password authentication. By default, this
        parameter is null.  </td> 
      </tr> 
      <tr class="alt">
        <td><span class="prop" container="smtp">password</span></td>
        <td><code>String</code></td>
        <td>The password value to use for plain user/password
        authentication. By default, this parameter is null.  
        </td>
      </tr>
      <tr> 
        <td><span class="prop" container="smtp">STARTTLS</span> </td>
        <td><code>boolean</code></td> 
        <td>If this parameter is set to true, then this appender
        will issue the STARTTLS command (if the server supports it)
        causing the connection to switch to SSL. Note that the
        connection is initially non-encrypted. By default, this
        parameter is set to false.
        </td> 
      </tr>
      <tr>
        <td><span class="prop" container="smtp">SSL</span></td>
        <td><code>boolean</code></td> <td>If this parameter is set to
        true, then this appender will open an SSL connection to the
        server. By default, this parameter is set to false.  </td>
      </tr>

      <tr>
        <td><span class="prop" container="smtp">charsetEncoding</span></td>
        <td><code>String</code></td>
        <td>The outgoing email message will be encoded in the
        designated <a
        href="https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html">charset</a>. The
        default charset encoding is "UTF-8" which works well for most
        purposes.
        </td>
      </tr>


      <tr>
        <td><span class="prop" container="smtp">localhost</span></td>
        <td><code>String</code></td>
        <td>In case the hostname of the SMTP client is not properly
        configured, e.g. if the client hostname is not fully
        qualified, certain SMTP servers may reject the HELO/EHLO
        commands sent by the client. To overcome this issue, you may
        set the value of the <span class="prop">localhost</span>
        property to the fully qualified name of the client host. See
        also the "mail.smtp.localhost" property in the documentation
        for the <a
        href="http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html">com.sun.mail.smtp</a>
        package.</td>
      </tr>

      <tr>
        <td><span class="prop" container="smtp">asynchronousSending</span></td>
        <td><code>boolean</code></td>
        <td>This property determines whether email transmission is
        done asynchronously or not. By default, the <span
        class="prop">asynchronousSending</span> property is
        'true'. However, under certain circumstances asynchronous
        sending may be inappropriate. For example if your application
        uses <code>SMTPAppender</code> to send alerts in response to a
        fatal error, and then exits, the relevant thread may not have
        the time to send the alert email. In this case, set <span
        class="prop">asynchronousSending</span> property to 'false'
        for synchronous email transmission.
        </td>
      </tr>

      <tr>
        <td><span class="prop" container="smtp">includeCallerData</span></td>
        <td><code>boolean</code></td>
        <td>By default, <span class="prop">includeCallerData</span> is
        set to <code>false</code>. You should set <span
        class="prop">includeCallerData</span> to <code>true</code> if
        <span class="prop">asynchronousSending</span> is enabled and
        you wish to include caller data in the logs. </td>
      </tr>

      <tr>
        <td><span class="prop" container="smtp">sessionViaJNDI</span></td>
        <td><code>boolean</code></td>
        <td><code>SMTPAppender</code> relies on
        <code>javax.mail.Session</code> to send out email messages. By
        default, <span class="prop">sessionViaJNDI</span> is set to
        <code>false</code> so the <code>javax.mail.Session</code>
        instance is built by <code>SMTPAppender</code> itself with the
        properties specified by the user. If the <span
        class="prop">sessionViaJNDI</span> property is set to
        <code>true</code>, the <code>javax.mail.Session</code> object
        will be retrieved via JNDI. See also the <span
        class="prop">jndiLocation</span> property.

        <p>Retrieving the <code>Session</code> via JNDI can reduce the
        number of places you need to configure/reconfigure the same
        information, making your application <a
        href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">dryer</a>. For
        more information on configuring resources in Tomcat see <a
        href="http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html#JavaMail_Sessions">JNDI
        Resources How-to</a>. <span class="label">beware</span> As
        noted in that document, make sure to remove <em>mail.jar</em>
        and <em>activation.jar</em> from your web-applications
        <em>WEB-INF/lib</em> folder when retrieving the
        <code>Session</code> from JNDI.
        </p>
        </td>
      </tr>

      <tr>
        <td><span class="prop" container="smtp">jndiLocation</span></td>
        <td><code>String</code></td>
        <td>The location where the javax.mail.Session is placed in
        JNDI. By default, <span class="prop">jndiLocation</span> is
        set to <span style="white-space:nowrap">"java:comp/env/mail/Session"</span>.
        </td>
      </tr>

		</table>		
		
		<p>The <code>SMTPAppender</code> keeps only the last 256 logging
		events in its cyclic buffer, throwing away older events when its
		buffer becomes full.  Thus, the number of logging events delivered
		in any e-mail sent by <code>SMTPAppender</code> is upper-bounded
		by 256. This keeps memory requirements bounded while still
		delivering a reasonable amount of application context.
		</p>
		
		<p>The <code>SMTPAppender</code> relies on the JavaMail API.  It
		has been tested with JavaMail API version 1.4.  The JavaMail API
		requires the JavaBeans Activation Framework package.  You can
		download the <a
		href="http://java.sun.com/products/javamail/">JavaMail API</a> and
		the <a
		href="http://java.sun.com/beans/glasgow/jaf.html">JavaBeans
		Activation Framework</a> from their respective websites.  Make
		sure to place these two jar files in the classpath before trying
		the following examples.
		</p>
		
		<p>A sample application, <a
		href="../xref/chapters/appenders/mail/EMail.html"><code>chapters.appenders.mail.EMail</code></a>
		generates a number of log messages followed by a single
		error message. It takes two parameters. The first parameter is an
		integer corresponding to the number of logging events to
		generate. The second parameter is the logback configuration
		file. The last logging event generated by <em>EMail</em>
		application, an ERROR, will trigger the transmission of an email
		message.
		</p>

		<p>Here is a sample configuration file intended for the
		<code>Email</code> application:
		</p>	
		
    <p class="example">Example: A sample <code>SMTPAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/mail/mail1.xml)</p>	

    <pre id="mail1" class="prettyprint source">&lt;configuration>	  
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    &lt;smtpHost>ADDRESS-OF-YOUR-SMTP-HOST&lt;/smtpHost>
    &lt;to>EMAIL-DESTINATION&lt;/to>
    &lt;to>ANOTHER_EMAIL_DESTINATION&lt;/to> &lt;!-- additional destinations are possible --&gt;
    &lt;from>SENDER-EMAIL&lt;/from>
    &lt;subject>TESTING: %logger{20} - %m&lt;/subject>
    &lt;layout class="ch.qos.logback.classic.PatternLayout">
      &lt;pattern>%date %-5level %logger{35} - %message%n&lt;/pattern>
    &lt;/layout>	    
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="EMAIL" />
  &lt;/root>  
&lt;/configuration></pre>

		<p>Before trying out <code>chapters.appenders.mail.Email</code> application
		with the above configuration file, you must set the <span
		class="prop">smtpHost</span>, <span class="prop">to</span> and
		<span class="prop">from</span> properties to values appropriate for
		your environment. Once you have set the correct values in the
		configuration file, execute the following command:
		</p>
		
<div class="source">java chapters.appenders.mail.EMail 100 src/main/java/chapters/appenders/mail/mail1.xml</div>

		<p>The recipient you specified should receive an email message
		containing 100 logging events formatted by
		<code>PatternLayout</code> The figure below is the resulting email
		message as shown by Mozilla Thunderbird.
		</p>
    
    <p><img src="images/chapters/appenders/smtpAppender1.jpg" alt="resulting email"/></p>
		
		<p>In the next example configuration file <em>mail2.xml</em>, the
		values for the <span class="prop">smtpHost</span>, <span
		class="prop">to</span> and <span class="prop">from</span>
		properties are determined by variable substitution. Here is the
		relevant part of <em>mail2.xml</em>.
		</p>		

    <pre class="prettyprint source">&lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
  &lt;smtpHost>${smtpHost}&lt;/smtpHost>
  &lt;to>${to}&lt;/to>
  &lt;from>${from}&lt;/from>
  &lt;layout class="ch.qos.logback.classic.html.HTMLLayout"/>
&lt;/appender></pre>
		
		<p>You can pass the required parameters on the command line:</p>
		
<div class="source"><pre>java -Dfrom=source@xyz.com -Dto=recipient@xyz.com -DsmtpHost=some_smtp_host \
  chapters.appenders.mail.EMail 10000 src/main/java/chapters/appenders/mail/mail2.xml
</pre></div>

		<p>Be sure to replace with values as appropriate for your
		environment.
		</p>
		
		<p>Note that in this latest example, <code>PatternLayout</code>
		was replaced by <code>HTMLLayout</code> which formats logs as an
		HTML table. You can change the list and order of columns as well
		as the CSS of the table. Please refer to <a
		href="layouts.html#ClassicHTMLLayout">HTMLLayout</a> documentation
		for further details.
    </p>
    
    <p>Given that the size of the cyclic buffer is 256, the recipient
    should see an email message containing 256 events conveniently
    formatted in an HTML table. Note that this run of the
    <code>chapters.appenders.mail.Email</code> application generated
    10'000 events of which only the last 256 were included in the
    outgoing email.
		</p>
		
    <p><img src="images/chapters/appenders/smtpAppender2.jpg" alt="2nd email"/></p>

    <p>Email clients such as Mozilla Thunderbird, Eudora or MS
    Outlook, offer reasonably good CSS support for HTML email.
    However, they sometimes automatically downgrade HTML to
    plaintext. For example, to view HTML email in Thunderbird, the
    "View&rarr;Message&nbsp;Body&nbsp;As&rarr;Original HTML" option
    must be set. Yahoo! Mail's support for HTML email, in particular
    its CSS support is very good. Gmail on the other hand, while it
    honors the basic HTML table structure, ignores the internal CSS
    formatting. Gmail supports inline CSS formatting but since inline
    CSS would make the resulting output too voluminous,
    <code>HTMLLayout</code> does not use inline CSS.
    </p>

    <h3 class="doAnchor" name="cyclicBufferSize">Custom buffer
    size</h3>

    <p>By default, the outgoing message will contain the last 256
    messages seen by <code>SMTPAppender</code>. If your heart so
    desires, you may set a different buffer size as shown in the next example.
    </p>

   <p class="example">Example:  <code>SMTPAppender</code> configuration with a custom bufer size (logback-examples/src/main/resources/chapters/appenders/mail/customBufferSize.xml)</p>	
    <pre class="prettyprint source">&lt;configuration>   
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    &lt;smtpHost>${smtpHost}&lt;/smtpHost>
    &lt;to>${to}&lt;/to>
    &lt;from>${from}&lt;/from>
    &lt;subject>%logger{20} - %m&lt;/subject>
    &lt;layout class="ch.qos.logback.classic.html.HTMLLayout"/>

    <b>&lt;cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker"></b>
      <b>&lt;!-- send just one log entry per email --></b>
      <b>&lt;bufferSize>1&lt;/bufferSize></b>
    <b>&lt;/cyclicBufferTracker></b>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="EMAIL" />
  &lt;/root>  
&lt;/configuration>    </pre>
    

    <h3 class="doAnchor">Triggering event</h3>

    <p>If the Evaluator property is not set, the
    <code>SMTPAppender</code> defaults to an <a
    href="../xref/ch/qos/logback/classic/boolex/OnErrorEvaluator.html">OnErrorEvaluator</a>
    instance which triggers email transmission when it encounters an
    event of level ERROR. While triggering an outgoing email in
    response to an error is relatively reasonable, it is possible to
    override this default behavior by providing a different
    implementation of the <code>EventEvaluator</code> interface.
    </p>
		
		<p>The <code>SMTPAppender</code> submits each incoming event to
		its evaluator by calling <code>evaluate()</code> method in order
		to check whether the event should trigger an email or just be
		placed in the cyclic buffer.  When the evaluator gives a positive
		answer to its evaluation, an email is sent out.  The
		<code>SMTPAppender</code> contains one and only one evaluator
		object.  This object may manage its own internal state. For
		illustrative purposes, the <code>CounterBasedEvaluator</code>
		class listed next implements an event evaluator whereby every
		1024th event triggers an email message.
		</p>

    <p class="example">Example: A <code>EventEvaluator</code> implementation
that evaluates to <code>true</code> every 1024th event (<a href="../xref/chapters/appenders/mail/CounterBasedEvaluator.html">logback-examples/src/main/java/chapters/appenders/mail/CounterBasedEvaluator.java</a>)</p>
   
   <pre class="prettyprint source">package chapters.appenders.mail;

import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluator;
import ch.qos.logback.core.spi.ContextAwareBase;

public class CounterBasedEvaluator extends ContextAwareBase implements EventEvaluator {

  static int LIMIT = 1024;
  int counter = 0;
  String name;

  <b>public boolean evaluate(Object event) throws NullPointerException,
      EvaluationException {
    counter++;

    if (counter == LIMIT) {
      counter = 0;

      return true;
    } else {
      return false;
    }
  }</b>

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}</pre>

		<p>Note that this class extends <code>ContextAwareBase</code> and
		implements <code>EventEvaluator</code>. This allows the user to
		concentrate on the core functions of her
		<code>EventEvaluator</code> and let the base class provide the
		common functionality.
		</p>

		<p>Setting the <span class="prop">Evaluator</span> option of
		<code>SMTPAppender</code> instructs it to use a custom evaluator.
		The next configuration file attaches a <code>SMTPAppender</code>
		to the root logger.  This appender uses a
		<code>CounterBasedEvaluator</code> instance as its event
		evaluator.
		</p>

    <p class="example">Example: <code>SMTPAppender</code> with custom 
    <code>Evaluator</code> and buffer size (logback-examples/src/main/resources/chapters/appenders/mail/mail3.xml)</p>

    <pre id="mail3" class="prettyprint source">&lt;configuration>
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    <b>&lt;evaluator class="chapters.appenders.mail.CounterBasedEvaluator" /></b>
    &lt;smtpHost>${smtpHost}&lt;/smtpHost>
    &lt;to>${to}&lt;/to>
    &lt;from>${from}&lt;/from>
    &lt;subject>%logger{20} - %m&lt;/subject>

    &lt;layout class="ch.qos.logback.classic.html.HTMLLayout"/>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="EMAIL" />
  &lt;/root>  
&lt;/configuration></pre>
    

    <h3 class="doAnchor" name="OnMarkerEvaluator">Marker based
    triggering </h3>

    <p>Although reasonable, the default triggering policy whereby every
    event of level ERROR triggers an outgoing email may result in too
    many emails, cluttering the targeted user's mailbox. Logback ships
    with another triggering policy, called <a
    href="../xref/ch/qos/logback/classic/boolex/OnMarkerEvaluator.html">OnMarkerEvaluator</a>. It
    is based on markers. In essence, emails are triggered only if the
    event is marked with a user-specified marker. The next example
    should make the point clearer.
    </p>

    <p>The <a
    href="../xref/chapters/appenders/mail/Marked_EMail.html">Marked_EMail</a>
    application contains several logging statements some of which are
    of level ERROR. One noteworthy statement contains a marker. Here
    is the relevant code.
    </p>

    <pre class="prettyprint source">Marker notifyAdmin = MarkerFactory.getMarker("NOTIFY_ADMIN");
logger.error(<b>notifyAdmin</b>,
  "This is a serious an error requiring the admin's attention",
   new Exception("Just testing"));</pre>

   <p>The next configuration file will trigger outgoing emails only in
   presence of events bearing the NOTIFY_ADMIN or the
   TRANSACTION_FAILURE markers.
   </p>

   <p class="example">Example: <code>SMTPAppender</code> with 
   <code>OnMarkerEvaluator</code> (logback-examples/src/main/resources/chapters/appenders/mail/mailWithMarker.xml)</p>


   <pre id="mailWithMarker" class="prettyprint source">&lt;configuration>
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    <b>&lt;evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator">
      &lt;marker>NOTIFY_ADMIN&lt;/marker>
      &lt;!-- you specify add as many markers as you want -->
      &lt;marker>TRANSACTION_FAILURE&lt;/marker>
    &lt;/evaluator></b>
    &lt;smtpHost>${smtpHost}&lt;/smtpHost>
    &lt;to>${to}&lt;/to>
    &lt;from>${from}&lt;/from>
    &lt;layout class="ch.qos.logback.classic.html.HTMLLayout"/>
  &lt;/appender>

  &lt;root>
    &lt;level value ="debug"/>
    &lt;appender-ref ref="EMAIL" />
  &lt;/root>  
&lt;/configuration></pre>
    
    <p>Give it a whirl with the following command:</p>

    <pre class="source">java -Dfrom=source@xyz.com -Dto=recipient@xyz.com -DsmtpHost=some_smtp_host \
  chapters.appenders.mail.Marked_EMail src/main/java/chapters/appenders/mail/mailWithMarker.xml</pre>


  <h4 class="doAnchor" name="marker_JaninoEventEvaluator">Marker-based
  triggering with JaninoEventEvaluator</h4>

    <p>Note that instead of using the marker-centric
    <code>OnMarkerEvaluator</code>, we could use the much more generic
    <a
    href="filters.html#JaninoEventEvaluator"><code>JaninoEventEvaluator</code></a>
    or its even more powerful cousin <a
    href="filters.html#GEventEvaluator"><code>GEventEvaluator</code></a>.
    For example, the following configuration file uses
    <code>JaninoEventEvaluator</code> instead of
    <code>OnMarkerEvaluator</code> but is otherwise equivalent to the
    previous configuration file.
    </p>

    <p class="example">Example: <code>SMTPAppender</code> with 
   <code>JaninoEventEvaluator</code> (logback-examples/src/main/resources/chapters/appenders/mail/mailWithMarker_Janino.xml)</p>

    <pre id="mailWithMarker_Janino" class="prettyprint source">&lt;configuration>
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    &lt;evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
      &lt;expression>
        (marker != null) &amp;&amp;
        (marker.contains("NOTIFY_ADMIN") || marker.contains("TRANSACTION_FAILURE"))
      &lt;/expression>
    &lt;/evaluator>    
    ... same as above
  &lt;/appender>
&lt;/configuration></pre>

    <h4 class="doAnchor" name="marker_GEventEvaluator">Marker-based
    triggering with GEventEvaluator</h4>

    <p>Here is the equivalent evaluator using <a
    href="filters.html#GEventEvaluator">GEventEvaluator</a>.</p>

    <p class="example">Example: the same with 
   <code>GEventEvaluator</code> (logback-examples/src/main/resources/chapters/appenders/mail/mailWithMarker_GEvent.xml)</p>


   <pre id="mailWithMarker_GEventEvaluator" class="prettyprint source">&lt;configuration>
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    &lt;evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator">
      &lt;expression>
        e.marker?.contains("NOTIFY_ADMIN") || e.marker?.contains("TRANSACTION_FAILURE")
      &lt;/expression>
    &lt;/evaluator>    
    ... same as above
  &lt;/appender>
&lt;/configuration></pre>

    <p>Note that since the event may lack a marker, the value of
    e.marker can be null. Hence the use of Groovy's <a
    href="http://groovy.codehaus.org/Null+Object+Pattern">safe
    dereferencing operator</a>, that is the .? operator.
    </p>


    <h3 class="doAnchor" name="smtpAuthentication">Authentication/STARTTLS/SSL</h3>

    <p><code>SMTPAppender</code> supports authentication via plain
    user passwords as well as both the STARTTLS and SSL
    protocols. Note that STARTTLS differs from SSL in that, in
    STARTTLS, the connection is initially non-encrypted and only after
    the STARTTLS command is issued by the client (if the server
    supports it) does the connection switch to SSL. In SSL mode, the
    connection is encrypted right from the start.
    </p>

    <h3 class="doAnchor" name="gmailSSL">SMTPAppender configuration
    for Gmail (SSL)</h3>

    <p>The next example shows you how to configure
    <code>SMTPAppender</code> for Gmail with the SSL protocol. </p>
    
    <p class="example">Example:: <code>SMTPAppender</code> to Gmail
    using SSL
    (logback-examples/src/main/resources/chapters/appenders/mail/gmailSSL.xml)</p>

    <pre id="gmailSSLExample" class="prettyprint source">&lt;configuration>
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    <b>&lt;smtpHost>smtp.gmail.com&lt;/smtpHost></b>
    <b>&lt;smtpPort>465&lt;/smtpPort></b>
    <b>&lt;SSL>true&lt;/SSL></b>
    <b>&lt;username>YOUR_USERNAME@gmail.com&lt;/username></b>
    <b>&lt;password>YOUR_GMAIL_PASSWORD&lt;/password></b>

    &lt;to>EMAIL-DESTINATION&lt;/to>
    &lt;to>ANOTHER_EMAIL_DESTINATION&lt;/to> &lt;!-- additional destinations are possible -->
    &lt;from>YOUR_USERNAME@gmail.com&lt;/from>
    &lt;subject>TESTING: %logger{20} - %m&lt;/subject>
    &lt;layout class="ch.qos.logback.classic.PatternLayout">
      &lt;pattern>%date %-5level %logger{35} - %message%n&lt;/pattern>
    &lt;/layout>	    
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="EMAIL" />
  &lt;/root>  
&lt;/configuration></pre>


    <h3 class="doAnchor" name="gmailSTARTTLS">SMTPAppender for Gmail
    (STARTTLS)</h3>

    <p>The next example shows you how to configure
    <code>SMTPAppender</code> for Gmail for the STARTTLS protocol. </p>

    <p class="example">Example: <code>SMTPAppender</code> to GMAIL using STARTTLS (logback-examples/src/main/resources/chapters/appenders/mail/gmailSTARTTLS.xml)</p>


    <pre id="gmailSTARTTLSExample" class="prettyprint source">&lt;configuration>	  
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    &lt;smtpHost>smtp.gmail.com&lt;/smtpHost>
    &lt;smtpPort>587&lt;/smtpPort>
    &lt;STARTTLS>true&lt;/STARTTLS>
    &lt;username>YOUR_USERNAME@gmail.com&lt;/username>
    &lt;password>YOUR_GMAIL_xPASSWORD&lt;/password>
    
    &lt;to>EMAIL-DESTINATION&lt;/to>
    &lt;to>ANOTHER_EMAIL_DESTINATION&lt;/to> &lt;!-- additional destinations are possible -->
    &lt;from>YOUR_USERNAME@gmail.com&lt;/from>
    &lt;subject>TESTING: %logger{20} - %m&lt;/subject>
    &lt;layout class="ch.qos.logback.classic.PatternLayout">
      &lt;pattern>%date %-5level %logger - %message%n&lt;/pattern>
    &lt;/layout>	    
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="EMAIL" />
  &lt;/root>  
&lt;/configuration></pre>


    <h3 class="doAnchor" name="smtpDiscriminator">SMTPAppender with MDCDiscriminator</h3>


    <p>As mentioned earlier, by specifying a discriminator other than
    the default one, <code>SMTPAppender</code> will generate email
    messages containing events pertaining to a particular user, user
    session or client IP address, depending on the specified discriminator.
    </p>

    <p>The next example illustrates the use of <a
    href="../xref/ch/qos/logback/classic/sift/MDCBasedDiscriminator.html">MDCBasedDiscriminator</a>
    in conjunction with the MDC key named "req.remoteHost", assumed to
    contain the IP address of the remote host accessing a fictitious
    application. In a web-application, you could use <a
    href="mdc.html#mis">MDCInsertingServletFilter</a> to populate MDC
    values.
    </p>

    <p class="example">Example: <code>SMTPAppender</code> with
    MDCBasedDsicriminator
    (logback-examples/src/main/resources/chapters/appenders/mail/mailWithMDCBasedDiscriminator.xml)</p>

    <pre id="mailWithMDCBasedDiscriminator" class="prettyprint source">&lt;configuration>	  
  &lt;appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    &lt;smtpHost>ADDRESS-OF-YOUR-SMTP-HOST&lt;/smtpHost>
    &lt;to>EMAIL-DESTINATION&lt;/to>
    &lt;from>SENDER-EMAIL&lt;/from>

    <b>&lt;discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator"></b>
      <b>&lt;key>req.remoteHost&lt;/key></b>
      <b>&lt;defaultValue>default&lt;/defaultValue></b>
    <b>&lt;/discriminator></b>

    &lt;subject>${HOSTNAME} -- %X{req.remoteHost} %msg"&lt;/subject>
    &lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
      &lt;pattern>%date%level%thread%X{req.remoteHost}%X{req.requestURL}%logger%msg&lt;/pattern>
    &lt;/layout>
  &lt;/appender>

  &lt;root>
    &lt;level level="DEBUG"/>
    &lt;appender-ref ref="EMAIL" />
  &lt;/root>  
&lt;/configuration></pre>

    <p>Thus, each outgoing email generated by
    <code>SMTPAppender</code> will belong to a <em>unique</em> remote
    host, greatly facilitating problem diagnosis.
    </p>
    
    <h4 class="doAnchor" name= "bufferManagement">Buffer management in
    very busy systems</h4>

    <p>Internally, each distinct value returned by the discriminator
    will cause the creation of a new cyclic buffer. However, at most
    <span class="prop">maxNumberOfBuffers</span> (by default 64)
    will be maintained.  Whenever the number of buffers rises above
    <span class="prop">maxNumberOfBuffers</span>, the least recently
    updated buffer is automatically discarded. As a second safety
    measure, any buffer which has not been updated in the last 30
    minutes will be automatically discarded as well.</p>

    <p>On systems serving a large number of transactions per minute,
    allowing only a small number for <span
    class="prop">maxNumberOfBuffers</span> (by default 64) will
    often cause the number of events in the outgoing email to be
    unnecessarily small. Indeed, in the presence of a large number of
    transactions, there will be more than one buffer associated with
    the same transaction as buffers will be killed and re-born in
    succession for the same discriminator value (or transaction). Note
    that in even such very busy systems, the maximum number of cyclic
    buffers is capped by <span
    class="prop">maxNumberOfBuffers</span>.
    </p>

    <p>To avoid such yo-yo effects, <code>SMTPAppender</code> will
    release the buffer associated with a given discriminator key as
    soon as it sees an event marked as "FINALIZE_SESSION". This will
    cause the appropriate buffer to be discarded at the end of each
    transaction. You can then safely increase the value of <span
    class="prop">maxNumberOfBuffers</span> to a larger value such as
    512 or 1024 without risking running out of memory.
    </p>

    <p>There are three distinct but complementary mechanisms working
    together to manage cyclic buffers. They ensure that only relevant
    buffers are kept alive at any given moment, even in very busy
    systems.</p>

    <!-- =========================================================== -->
    <!-- =========================================================== -->


    <h3 class="doAnchor" name="DBAppender">DBAppender</h3>
		
		<p>The <a
		href="../xref/ch/qos/logback/classic/db/DBAppender.html"><code>DBAppender</code></a>
		inserts logging events into three database tables in a format
		independent of the Java programming language.
		</p>

		<p>These three tables are <em>logging_event</em>,
		<em>logging_event_property</em> and
		<em>logging_event_exception</em>. They must exist before
		<code>DBAppender</code> can be used. Logback ships with SQL
		scripts that will create the tables.  They can be found under the
		<em>logback-classic/src/main/java/ch/qos/logback/classic/db/script</em>
		folder. There is a specific script for each of the most popular
		database systems.  If the script for your particular type of
		database system is missing, it should be quite easy to write one,
		taking example on the already existing scripts. If you send them
		to us, we will gladly include missing scripts in future releases.
		</p>

		<p>If your JDBC driver supports the <code>getGeneratedKeys</code>
		method introduced in JDBC 3.0 specification, assuming you have
		created the appropriate database tables as mentioned above, then
		no additional steps are required. Otherwise, there must be an
		<code>SQLDialect</code> appropriate for your database
		system. Currently, logback has dialects for H2, HSQL, MS SQL
		Server, MySQL, Oracle, PostgreSQL, SQLLite and Sybase. </p>

		<p>The table below summarizes the database types and their support
		of the <code>getGeneratedKeys()</code> method.
		</p>

		<table class="bodyTable striped" border="0" cellpadding="4">
			<tr>
				<th>RDBMS</th>
        <th>tested version(s)
        </th>
        <th>tested JDBC driver version(s)
				</th>
        <th>
					supports
					<br />
					<code>getGeneratedKeys()</code>
					method
				</th>		

        <th>is a dialect <br/>provided by logback</th>
			</tr>

      <tr>
				<td>DB2</td>
        <td>untested</td>
				<td>untested</td>
				<td>unknown</td>
        <td>NO</td>
			</tr>

      <tr>
        <td>H2</td>
        <td>1.2.132</td>
        <td>-</td>
				<td>unknown</td>
        <td>YES</td>
			</tr>

      <tr>
        <td>HSQL</td>
        <td>1.8.0.7</td>
        <td>-</td>
				<td>NO </td>
        <td>YES</td>
			</tr>

      <tr>
        <td>Microsoft SQL Server</td>
        <td>2005</td>
        <td>2.0.1008.2 (sqljdbc.jar)</td>
				<td>YES</td>
        <td>YES</td>
			</tr>

      <tr>
				<td>MySQL</td>
        <td>5.0.22</td>
        <td>5.0.8 (mysql-connector.jar)</td>        
				<td>YES</td>
        <td>YES</td>
			</tr>

			<tr>
				<td>PostgreSQL</td>
        <td>8.x</td>
        <td>8.4-701.jdbc4</td>
				<td>NO</td>
        <td>YES</td>

			</tr>
		
			<tr>
				<td>Oracle</td>
        <td>10g</td>
        <td>10.2.0.1 (ojdbc14.jar)</td>
				<td>YES</td>
        <td>YES</td>
			</tr>
	
      <tr>
        <td>SQLLite</td>
        <td>3.7.4</td>
        <td>-</td>
        <td>unknown</td>
        <td>YES</td>
      </tr>
	
			
      <tr>
        <td>Sybase SQLAnywhere</td>
        <td>10.0.1</td>
        <td>-</td>
        <td>unknown</td>
        <td>YES</td>
      </tr>

		</table>
		
		<p>Experiments show that writing a single event into the database
		takes approximately 10 milliseconds, on a "standard" PC. If pooled
		connections are used, this figure drops to around 1
		millisecond. Note that most JDBC drivers already ship with
		connection pooling support.
		</p>
		
		<p>Configuring logback to use <code>DBAppender</code> can be done
		in several different ways, depending on the tools one has to
		connect to the database, and the database itself. The key issue in
		configuring <code>DBAppender</code> is about setting its
		<code>ConnectionSource</code> object, as we shall discover
		shortly.
		</p>
		
		<p>Once <code>DBAppender</code> is configured for your database,
		logging events are sent to the specified database. As stated
		previously, there are three tables used by logback to store
		logging event data.
		</p>
		
		<p>
			The <em>logging_event</em> table contains the following fields:
		</p>
		<table class="bodyTable striped">
			<tr>
				<th>Field</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td><b>timestamp</b></td>
				<td><code>big int</code></td>
				<td>The timestamp that was valid at the logging event's creation.</td>
			</tr>
			<tr>
				<td><b>formatted_message</b></td>
				<td><code>text</code></td>

				<td>The message that has been added to the logging event,
				after formatting with
				<code>org.slf4j.impl.MessageFormatter</code>, in case objects
				were passed along with the message.</td>
			</tr>
			<tr>
				<td><b>logger_name</b></td>
				<td><code>varchar</code></td>
				<td>The name of the logger used to issue the logging request.</td>
			</tr>
			<tr>
				<td><b>level_string</b></td>
				<td><code>varchar</code></td>
				<td>The level of the logging event.</td>
			</tr>
			<tr>
				<td><b>reference_flag</b></td>
				<td><code>smallint</code></td>
				<td>
					<p>This field is used by logback to identify logging events
					that have an exception or <code>MDC</code>property values
					associated.
					</p>

					<p>Its value is computed by
					<code>ch.qos.logback.classic.db.DBHelper</code>. A logging
					event that contains <code>MDC</code> or <code>Context</code>
					properties has a flag number of <em>1</em>. One that
					contains an exception has a flag number of <em>2</em>. A
					logging event that contains both elements has a flag number
					of <em>3</em>.
					</p>
				</td>
			</tr>
			<tr>
				<td><b>caller_filename</b></td>
				<td><code>varchar</code></td>
				<td>The name of the file where the logging request was issued.</td>
			</tr>
			<tr>
				<td><b>caller_class</b></td>
				<td><code>varchar</code></td>
				<td>The class where the logging request was issued.</td>
			</tr>
			<tr>
				<td><b>caller_method</b></td>
				<td><code>varchar</code></td>
				<td>The name of the method where the logging request was issued.</td>
			</tr>
			<tr>
				<td><b>caller_line</b></td>
				<td><code>char</code></td>
				<td>The line number where the logging request was issued.</td>
			</tr>
			<tr>
				<td><b>event_id</b></td>
				<td><code>int</code></td>
				<td>The database id of the logging event.</td>
			</tr>
		</table>
		
		<p>
			The <em>logging_event_property</em> is used to store the keys and values
			contained in the <code>MDC</code> or the <code>Context</code>. 
			It contains these fields:
		</p>

		<table class="bodyTable striped">
			<tr>
				<th>Field</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td><b>event_id</b></td>
				<td><code>int</code></td>
				<td>The database id of the logging event.</td>
			</tr>
			<tr>
				<td><b>mapped_key</b></td>
				<td><code>varchar</code></td>
				<td>The key of the <code>MDC</code> property</td>
			</tr>		
			<tr>
				<td><b>mapped_value</b></td>
				<td><code>text</code></td>
				<td>The value of the <code>MDC</code> property</td>
			</tr>				
		</table>
		
		<p>
			The <em>logging_event_exception</em> table contains the following fields:
		</p>
		
		<table class="bodyTable striped">
			<tr>
				<th>Field</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td><b>event_id</b></td>
				<td><code>int</code></td>
				<td>The database id of the logging event.</td>
			</tr>
			<tr>
				<td><b>i</b></td>
				<td><code>smallint</code></td>
				<td>The index of the line in the full stack trace.</td>
			</tr>		
			<tr>
				<td><b>trace_line</b></td>
				<td><code>varchar</code></td>
				<td>The corresponding line</td>
			</tr>				
		</table>
		
		<p>
			To give a more visual example of the work done by <code>DBAppender</code>, here
			is a screenshot of a MySQL database with content provided by <code>DBAppender</code>.
		</p>
		
		<p>The <em>logging_event</em> table:</p>

		<img src="images/chapters/appenders/dbAppenderLE.gif" alt="Logging Event table" />

		<p>The <em>logging_event_exception</em> table:</p>
		
		<img src="images/chapters/appenders/dbAppenderLEException.gif" alt="Logging Event Exception table" />

		<p>The <em>logging_event_property</em> table:</p>
		
		<img src="images/chapters/appenders/dbAppenderLEProperty.gif" alt="Logging Event Property table" />

		
		<h4>ConnectionSource</h4>
		
		<p>The <code>ConnectionSource</code> interface provides a
		pluggable means of transparently obtaining JDBC connections for
		logback classes that require the use of a
		<code>java.sql.Connection</code>. There are currently three
		implementations of <code>ConnectionSource</code>, namely
		<code>DataSourceConnectionSource</code>,
		<code>DriverManagerConnectionSource</code> and
		<code>JNDIConnectionSource</code>.
		</p>
		
		<p>
			The first example that we will review is a configuration using
			<code>DriverManagerConnectionSource</code> and a MySQL database.
			The following configuration file is what one would need.
		</p>
		
    <p class="example">Example: <code>DBAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/db/append-toMySQL-with-driverManager.xml)</p>

    <pre id="append-toMySQL-with-driverManager" class="prettyprint source">&lt;configuration>

  <b>&lt;appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    &lt;connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
      &lt;driverClass>com.mysql.jdbc.Driver&lt;/driverClass>
      &lt;url>jdbc:mysql://host_name:3306/datebase_name&lt;/url>
      &lt;user>username&lt;/user>
      &lt;password>password&lt;/password>
    &lt;/connectionSource>
  &lt;/appender></b>
  
  &lt;root level="DEBUG" >
    &lt;appender-ref ref="DB" />
  &lt;/root>
&lt;/configuration></pre>

		<p>
			The correct driver must be declared. Here, the <code>com.mysql.jdbc.Driver</code>
			class is used. The <span class="prop">url</span> must begin with <em>jdbc:mysql://</em>.
		</p>
		
		<p>
			The 
			<a href="../xref/ch/qos/logback/core/db/DriverManagerConnectionSource.html">
			<code>DriverManagerConnectionSource</code></a> is an implementation of
			<code>ConnectionSource</code> that obtains the connection in the
			traditional JDBC manner based on the connection URL.
		</p>
		<p>
			Note that this class will establish a new
			<code>Connection</code> for each call to
			<code>getConnection()</code>. It is recommended that you either
			use a JDBC driver that natively supports connection pooling or
			that you create your own implementation of
			<code>ConnectionSource</code> that taps into whatever pooling
			mechanism you are already using. If you have access to a JNDI
			implementation that supports <code>javax.sql.DataSource</code>,
			e.g. within a J2EE application server, see <a
			href="#JNDIConnectionSource"><code>JNDIConnectionSource</code></a>
			below.
		</p>
<!-- 
		
		HAS TO BE TESTED

		<p>
			If you do not have another connection pooling mechanism built
			into your application, you can use the
			<a href="http://jakarta.apache.org/commons/dbcp/index.html">
		  commons-dbcp </a> package from Apache:
		</p>

<pre class="prettyprint source">
  &lt;connectionSource
    class=&quot;ch.qos.logback.core.db.DriverManagerConnectionSource&quot;&gt;
    &lt;param name=&quot;driver&quot; value=&quot;org.apache.commons.dbcp.PoolingDriver&quot;/&gt; 
    &lt;param name=&quot;url&quot; value=&quot;jdbc:apache:commons:dbcp:/myPoolingDriver&quot;/&gt; 
  &lt;/connectionSource&gt;
</pre>
		
		<p>
			Then the configuration information for the commons-dbcp
			package goes into the file <em>myPoolingDriver.jocl</em> and is
			placed in the classpath. See the
			<a href="http://jakarta.apache.org/commons/dbcp/index.html"> commons-dbcp </a>
			documentation for details.
		</p>
 -->
 
		<p>Connecting to a database using a <code>DataSource</code> is
		rather similar.  The configuration now uses <a
		href="../xref/ch/qos/logback/core/db/DataSourceConnectionSource.html">
		<code>DataSourceConnectionSource</code></a>, which is an
		implementation of <code>ConnectionSource</code> that obtains the
		<code>Connection</code> in the recommended JDBC manner based on a
		<code>javax.sql.DataSource</code>.
		</p>
	
    <p class="example">Example: <code>DBAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/db/append-with-datasource.xml)</p>	


    <pre id="append-with-datasource" class="prettyprint source">&lt;configuration  debug="true">

  &lt;appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
     <b>&lt;connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
       
       &lt;dataSource class="${dataSourceClass}">
       	 </b>&lt;!-- Joran cannot substitute variables
       	 that are not attribute values. Therefore, we cannot
       	 declare the next parameter like the others. 
       	 -->
         <b>&lt;param name="${url-key:-url}" value="${url_value}"/>
         &lt;serverName>${serverName}&lt;/serverName>
         &lt;databaseName>${databaseName}&lt;/databaseName>
       &lt;/dataSource></b>
       
       &lt;user>${user}&lt;/user>
       &lt;password>${password}&lt;/password>
     &lt;/connectionSource>
  &lt;/appender>

  &lt;root level="INFO">
    &lt;appender-ref ref="DB" />
  &lt;/root>  
&lt;/configuration></pre>

		<p>Note that in this configuration sample, we make heavy use of
		substitution variables.  They are sometimes handy when connection
		details have to be centralized in a single configuration file and
		shared by logback and other frameworks.
		</p>	
		
<!-- TO BE TESTED 

     <p>The connection created by
     <code>DataSourceConnectionSource</code> can be placed in a JNDI
     context by using <code>BindDataSourceToJNDIAction</code>. In that
     case, one has to specify the use of this class by adding a new
     rule to Joran, logback's configuration framework. Here is an
     excerpt of such a configuration file.  </p>
		
<div class="source"><pre>&lt;configuration>
  ..
  <b>&lt;newRule pattern="configuration/bindDataSourceToJNDI" 
           actionClass="ch.qos.logback.core.db.BindDataSourceToJNDIAction"/>
  	    
  &lt;bindDataSourceToJNDI /></b>
  ..
&lt;/configuration></pre></div>

		<p> The <em>newRule</em> element teaches Joran to use specified
		action class with the given pattern.  Then, we simply declare the
		given element. The action class will be called and our connection
		source will be bound to a JNDI context.  </p>

		<p>This is a very powerful capability of Joran. If you'd like to
		read more about Joran, please see the <a
		href="onJoran.html">chapter to Joran</a>.  </p>
		
		-->

    <h4 class="doAnchor"
    name="JNDIConnectionSource">JNDIConnectionSource</h4>

		<p><a
		href="../xref/ch/qos/logback/core/db/JNDIConnectionSource.html">
		<code>JNDIConnectionSource</code></a> is another
		<code>ConnectionSource</code> implementation shipping in logback.
		As its name indicates, it retrieves a
		<code>javax.sql.DataSource</code> from a JNDI and then leverages
		it to obtain a <code>java.sql.Connection</code>
		instance. <code>JNDIConnectionSource</code> is primarily designed
		to be used inside J2EE application servers or by application
		server clients, assuming the application server supports remote
		access of <code>javax.sql.DataSource</code>.  Thus, one can take
		advantage of connection pooling and whatever other goodies the
		application server provides. More importantly, your application
		will be <a
		href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">dryer</a>
		as it will be no longer necessary to define a
		<code>DataSource</code> in <em>logback.xml</em>.</p>

    <p>For example, here is a configuration snippet for Tomcat. It
    assumes PostgreSQL as the database although any of the supported
    database systems (listed above) would work.</p>

<pre  class="prettyprint source">&lt;Context docBase="/path/to/app.war" path="/myapp">
  ...
  &lt;Resource <b>name="jdbc/logging"</b>
               auth="Container"
               type="javax.sql.DataSource"
               username="..."
               password="..."
               driverClassName="org.postgresql.Driver"
               url="jdbc:postgresql://localhost/..."
               maxActive="8"
               maxIdle="4"/>
  ...
&lt;/Context></pre>
		
   <p>Once a <code>DataSource</code> is defined in the J2EE server, it
   can be easily referenced by your logback configuration file, as
   shown in the next example.</p>
   
   <p class="example">Example: <code>DBAppender</code> configuration
   by <code>JNDIConnectionSource</code>
   (logback-examples/src/main/resources/chapters/appenders/db/append-via-jndi.xml)</p>

<pre id="append-via-jndi" class="prettyprint source">&lt;configuration debug="true">
  &lt;appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    &lt;connectionSource class=&quot;ch.qos.logback.core.db.JNDIConnectionSource&quot;&gt;
      <b>&lt;!-- please note the "java:comp/env/" prefix --&gt;</b>
      <b>&lt;jndiLocation>java:comp/env/jdbc/logging&lt;/jndiLocation></b>
    &lt;/connectionSource&gt;
  &lt;/appender>
  &lt;root level="INFO">
    &lt;appender-ref ref="DB" />
  &lt;/root>  
&lt;/configuration></pre>

		<p>
			Note that this class will obtain an
			<code>javax.naming.InitialContext</code>
			using the no-argument constructor. This will usually work
			when executing within a J2EE environment. When outside the
			J2EE environment, make sure that you provide a
			<em>jndi.properties</em>
			file as described by your JNDI provider's documentation.
		</p>
		
		<h4 class="doAnchor">Connection pooling</h4>
		
		<p>Logging events can be created at a rather fast pace. To keep up
		with the flow of events that must be inserted into a database, it
		is recommended to use connection pooling with
		<code>DBAppender</code>.
		</p>
		
		<p>
			Experiment shows that using connection pooling with <code>DBAppender</code>
			gives a big performance boost. With the following
			configuration file, logging events are sent to a MySQL database,
			without any pooling.
		</p>
    
    <p class="example">Example: <code>DBAppender</code> configuration
    without pooling
    (logback-examples/src/main/resources/chapters/appenders/db/append-toMySQL-with-datasource.xml)</p>

    <pre id="append-toMySQL-with-datasource" class="prettyprint source">&lt;configuration>

  &lt;appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    &lt;connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
      &lt;dataSource class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
        &lt;serverName>${serverName}&lt;/serverName>
        &lt;port>${port$&lt;/port>
        &lt;databaseName>${dbName}&lt;/databaseName>
        &lt;user>${user}&lt;/user>
        &lt;password>${pass}&lt;/password>
      &lt;/dataSource>
    &lt;/connectionSource>
  &lt;/appender>
    
  &lt;root level="DEBUG">
    &lt;appender-ref ref="DB" />
  &lt;/root>
&lt;/configuration></pre>

		<p>With this configuration file, sending 500 logging events to a
		MySQL database takes a whopping 5 seconds, that is 10 milliseconds
		per request. This figure is unacceptable when dealing with large
		applications.
		</p>

		<p>A dedicated external library is necessary to use connection
		pooling with <code>DBAppender</code>. The next example uses <a
		href="http://sourceforge.net/projects/c3p0">c3p0</a>. To be able
		to use c3p0, one must download it and place
		<em>c3p0-VERSION.jar</em> in the classpath.
		</p>

    <p class="example">Example: <code>DBAppender</code> configuration
    with pooling
    (logback-examples/src/main/resources/chapters/appenders/db/append-toMySQL-with-datasource-and-pooling.xml)</p>
    <pre id="append-toMySQL-with-datasource-and-pooling" class="prettyprint source">&lt;configuration>

  &lt;appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    &lt;connectionSource
      class="ch.qos.logback.core.db.DataSourceConnectionSource">
      <b>&lt;dataSource
        class="com.mchange.v2.c3p0.ComboPooledDataSource">
        &lt;driverClass>com.mysql.jdbc.Driver&lt;/driverClass>
        &lt;jdbcUrl>jdbc:mysql://${serverName}:${port}/${dbName}&lt;/jdbcUrl>
        &lt;user>${user}&lt;/user>
        &lt;password>${password}&lt;/password>
      &lt;/dataSource></b>
    &lt;/connectionSource>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="DB" />
  &lt;/root>
&lt;/configuration></pre>

		<p>With this new configuration, sending 500 logging requests to
		the aforementioned MySQL database takes around 0.5 seconds, for an
		average of 1 millisecond per request, that is a tenfold
		improvement in performance.
		</p>

		<h3 class="doAnchor" name="SyslogAppender">SyslogAppender</h3>

		<p>The syslog protocol is a very simple protocol: a syslog sender
		sends a small message to a syslog receiver.  The receiver is
		commonly called <em>syslog daemon</em> or <em>syslog server</em>.
		Logback can send messages to a remote syslog daemon. This is
		achieved by using <a
		href="../xref/ch/qos/logback/classic/net/SyslogAppender.html"><code>SyslogAppender</code></a>.
		</p>
		
		<p>Here are the properties you can pass to a SyslogAppender.</p>

		<table class="bodyTable striped">
			<tr>
				<th>Property Name</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td><span class="prop" container="syslog">syslogHost</span></td>
				<td><code>String</code></td>
				<td>The host name of the syslog server.</td>
			</tr>
			<tr>
				<td><span class="prop" container="syslog">port</span></td>
				<td><code>String</code></td>
				<td>The port number on the syslog server to connect
				to. Normally, one would not want to change the default value
				of <em>514</em>.
				</td>
			</tr>
			<tr>
				<td><span class="prop" container="syslog">facility</span></td>
				<td><code>String</code></td>
				<td>
					<p>The <span class="prop">facility</span> is meant to identify 
						the source of a message.</p>
					<p>The <span class="prop">facility</span> option must be set
					to one of the strings <em>KERN, USER, MAIL, DAEMON, AUTH,
					SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, NTP, AUDIT,
					ALERT, CLOCK, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4,
					LOCAL5, LOCAL6, LOCAL7</em>. Case is not important.</p>
				</td>
			</tr>
      <tr>
        <td><span class="prop" container="syslog">suffixPattern</span></td>
				<td><code>String</code></td>
				<td><p>The <span class="prop">suffixPattern</span> option
				specifies the format of the non-standardized part of the
				message sent to the syslog server. By default, its value is
				<em>[%thread] %logger %msg</em>. Any value that a
				<code>PatternLayout</code> could use is a correct <span
				class="prop">suffixPattern</span> value.
					</p>
				</td>
			</tr>

      <tr>
        <td><span class="prop"
        container="syslog">stackTracePattern</span></td>
				<td><code>String</code></td>
				<td><p>The <span class="prop">stackTracePattern</span>
				property allows the customization of the string appearing just
				before each stack trace line. The default value for this
				property is "\t", i.e. the tab character. Any value accepted
				by <code>PatternLayout</code> is a valid value for <span
				class="prop">stackTracePattern</span>.</p>
				</td>
			</tr>

			<tr>
				<td><span class="prop" container="syslog">throwableExcluded</span></td>
				<td><code>boolean</code></td>
				<td>Setting <span class="prop">throwableExcluded</span> to
				<code>true</code> will cause stack trace data associated with
				a Throwable to be omitted. By default, <span
				class="prop">throwableExcluded</span> is set to
				<code>false</code> so that stack trace data is sent to the
				syslog server. </td>
			</tr>


		</table>
		
		<p>The syslog severity of a logging event is converted from the
		level of the logging event.  The <em>DEBUG</em> level is converted
		to <em>7</em>, <em>INFO</em> is converted to <em>6</em>,
		<em>WARN</em> is converted to <em>4</em> and <em>ERROR</em> is
		converted to <em>3</em>.
		</p>
		
		<p>Since the format of a syslog request follows rather strict
		rules, there is no layout to be used with
		<code>SyslogAppender</code>. However, using the <span
		class="prop">suffixPattern</span> option lets the user display
		whatever information she wishes.
		</p>
		
		<p>Here is a sample configuration using a
		<code>SyslogAppender</code>.</p>
		
    <p class="example">Example: <code>SyslogAppender</code> configuration (logback-examples/src/main/resources/chapters/appenders/conf/logback-syslog.xml)</p>	

    <pre id="logback-syslog" class="prettyprint source">&lt;configuration>

  &lt;appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
    &lt;syslogHost>remote_home&lt;/syslogHost>
    &lt;facility>AUTH&lt;/facility>
    &lt;suffixPattern>[%thread] %logger %msg&lt;/suffixPattern>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="SYSLOG" />
  &lt;/root>
&lt;/configuration></pre>

		<p>When testing this configuration, you should verify that the
		remote syslog daemon accepts requests from an external
		source. Experience shows that, by default, syslog daemons usually
		deny requests coming via a network connection.
		</p>
		

    <h3 class="doAnchor" name="SiftingAppender">SiftingAppender</h3>

    <p>As its name implies, a <code>SiftingAppender</code> can be used
    to separate (or sift) logging according to a given runtime
    attribute. For example, <code>SiftingAppender</code> can separate
    logging events according to user sessions, so that the logs
    generated by different users go into distinct log files, one log
    file per user.
    </p>


    
    <table class="bodyTable striped">
			<tr>
				<th>Property Name</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td><span class="prop" container="sift">timeout</span></td>
				<td><code><a
				href="../apidocs/ch/qos/logback/core/util/Duration.html">Duration</a></code></td>
				<td>A nested appender which has not been accessed beyond the
				<span class="prop">timeout</span> duration is deemed stale. A
				stale appender is closed and unreferenced by
				<code>SiftingAppender</code>. The default value for <span
				class="prop">timeout</span> is 30 minutes.</td>
			</tr>
			<tr>
				<td><span class="prop" container="sift">maxAppenderCount</span></td>
				<td><code>integer</code></td>
				<td>The maximum number of nested appenders
				<code>SiftingAppender</code> may create and track. Default
				value for <span class="prop">maxAppenderCount</span> is
				Integer.MAX_VALUE.</td>
			</tr>
  </table>

    <p><code>SiftingAppender</code> achieves this feat by creating
    nested appenders on the fly. Nested appenders are created based on
    a template specified within the configuration of the
    <code>SiftingAppender</code> itself (enclosed within the
    <code>&lt;sift></code> element, see example
    below). <code>SiftingAppender</code> is responsible for managing
    the lifecycle of child appenders. For example,
    <code>SiftingAppender</code> will automatically close and remove
    any stale appender. A nested appender is considered stale when no
    accesses it beyond the duration specified by the <span
    class="prop">timeout</span> parameter.
    </p>

    <p>When handling a logging event, <code>SiftingAppender</code>
    will select a child appender to delegate to. The selection
    criteria are computed at runtime by a discriminator. The user can
    specify the selection criteria with the help of a <code><a
    href="../xref/ch/qos/logback/core/sift/Discriminator.html">Discriminator</a></code>. Let
    us now study an example.
    </p>
 
    <h4>Example</h4>

    <p>The <a
    href="../xref/chapters/appenders/sift/SiftExample.html">SiftExample</a>
    application logs a message stating that the application has
    started. It then sets the MDC key "userid" to "Alice" and logs a
    message. Here is the salient code:</p>
   
    <p class="source">logger.debug("Application started");
MDC.put("userid", "Alice");
logger.debug("Alice says hello"); </p>

    <p>The template for the configuration file illustrates the use of
    <code>SiftingAppender</code>.</p>


    <p class="example">Example: <code>SiftingAppender</code>
    configuration
    (logback-examples/src/main/resources/chapters/appenders/sift/byUserid.xml)</p>

    <pre id="byUserid" class="prettyprint source">&lt;configuration>

  <b>&lt;appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender"></b>
    &lt;!-- in the absence of the class attribute, it is assumed that the
         desired discriminator type is
         ch.qos.logback.classic.sift.MDCBasedDiscriminator -->
    <b>&lt;discriminator></b>
      <b>&lt;key><span class="green">userid</span>&lt;/key></b>
      <b>&lt;defaultValue>unknown&lt;/defaultValue></b>
    <b>&lt;/discriminator></b>
    <b>&lt;sift></b>
      <b>&lt;appender name="FILE-<span class="green">${userid}</span>" class="ch.qos.logback.core.FileAppender"></b>
        <b>&lt;file><span class="green">${userid}</span>.log&lt;/file></b>
        <b>&lt;append>false&lt;/append></b>
        <b>&lt;layout class="ch.qos.logback.classic.PatternLayout"></b>
          <b>&lt;pattern>%d [%thread] %level %mdc %logger{35} - %msg%n&lt;/pattern></b>
        <b>&lt;/layout></b>
      <b>&lt;/appender></b>
    <b>&lt;/sift></b>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="SIFT" />
  &lt;/root>
&lt;/configuration></pre>
    
    
    <p>In the absence of a class attribute, it is assumed that the
    discriminator type is <a
    href="../xref/ch/qos/logback/classic/sift/MDCBasedDiscriminator.html">MDCBasedDiscriminator</a>.
    The discriminating value is the MDC value associated with the key
    given by the <span class="prop">key</span> property. However, if
    that MDC value is null, then <span
    class="prop">defaultValue</span> is used as the discriminating
    value.
    </p>

    <p>The <code>SiftingAppender</code> is unique in its capacity to
    reference and configure child appenders. In the above example,
    <code>SiftingAppender</code> will create multiple
    <code>FileAppender</code> instances, each
    <code>FileAppender</code> instance identified by the value
    associated with the "userid" MDC key. Whenever the "userid" MDC
    key is assigned a new value, a new <code>FileAppender</code>
    instance will be built from scratch. The
    <code>SiftingAppender</code> keeps track of the appenders it
    creates. Appenders unused for 30 minutes will be automatically
    closed and discarded.
    </p>

    <p><span class="label notice">Variable export</span> It is not
    enough to have different appender instances; each instance must
    output to a distinct target resource. To allow such
    differentiation, within the appender template, the key passed to
    the discriminator, "userid" in the above example, is exported and
    becomes a <a
    href="configuration.html#variableSubstitution">variable</a>. Consequently,
    this variable can be used to differentiate the actual resource
    used by a given child appender.
    </p>

    <p>Running the <code>SiftExample</code> application with the
    "byUserid.xml" configuration file shown above, will result in two
    distinct log files, "unknown.log" and "Alice.log".
		</p>

    <p><span class="label">local-scoped variables</span> As of version
    1.0.12, properties defined in local scope within the configuration
    file will be available to nested appenders. Moreover, you can <a
    href="configuration.html#definingProps">define variables</a> or <a
    href="configuration.html#definingPropsOnTheFly">dynamically
    compute</a> variables from <em>within</em> the the
    <code>&lt;sift></code> element. Combining a variable from parts
    defined outside and within the <code>&lt;sift></code> element is
    also supported.
    </p>

    <h4 class="doAnchor" name="siftGettingTimeoutRight">Getting the
    <span class="prop">timeout</span> right</h4>

    <p>For certain types of applications, it may be difficult to get
    the <span class="prop">timeout</span> parameter right. If the
    <span class="prop">timeout</span> is too small, a nested appender
    might be removed just to be created anew a few seconds later. This
    phenomenon is called <em>trashing</em>. If the <span
    class="prop">timeout</span> is too long and appenders are created
    in quick succession, you might run out of resources. Similarly,
    setting <span class="prop">maxAppenderCount</span> too low might
    cause trashing as well.
    </p>

    <p>In many case, it may be easier to pinpoint a location in your
    code after which a nested appender is no longer needed. If such a
    location exists, even approximately, log from that location using
    the <a
    href="../apidocs/ch/qos/logback/classic/ClassicConstants.html#FINALIZE_SESSION_MARKER">FINALIZE_SESSION</a>
    marker. Whenever SiftingAppender sees a logging event marked as
    <code>FINALIZE_SESSION</code> it will end-of-life the associated
    nested appender. Upon reaching its end-of-life, a nested appender
    will linger for a few seconds to process any late coming events
    (if any) and then will be closed.
    </p>
    
    <pre class="prettyprint source">import org.slf4j.Logger;
import static ch.qos.logback.classic.ClassicConstants.FINALIZE_SESSION_MARKER;

  void job(String jobId) {
   
    MDC.put("jobId", jobId);
    logger.info("Starting job.");

    ... do whather the job needs to do
    
    // will cause the nested appender reach end-of-life. It will
    // linger for a few seconds.
    logger.info(FINALIZE_SESSION_MARKER, "About to end the job");

    try {
      .. perform clean up
    } catch(Exception e);  
      // This log statement will be handled by the lingering appender. 
      // No new appender will be created.
      logger.error("unexpected error while cleaning up", e);
    }
  }

</pre>

    <h3 class="doAnchor" name="AsyncAppender">AsyncAppender</h3>

    <p>AsyncAppender logs <a
    href="../apidocs/ch/qos/logback/classic/spi/ILoggingEvent.html">ILoggingEvent</a>s
    asynchronously. It acts solely as an event dispatcher and must
    therefore reference another appender in order to do anything
    useful.</p>

    <p><span class="label notice">Lossy by default if 80% full</span>
    AsyncAppender buffers events in a <a
    href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html">
    BlockingQueue</a>. A worker thread created by
    <code>AsyncAppender</code> takes events from the head of the
    queue, and dispatches them to the single appender attached to
    <code>AsyncAppender</code>. Note that by default,
    <code>AsyncAppender</code> will drop events of level TRACE, DEBUG
    and INFO if its queue is 80% full. This strategy has an amazingly
    favorable effect on performance at the cost of event loss.
    </p>

    <p><span class="label">Application stop/redeploy</span> Upon
    application shutdown or redeploy, <code>AsyncAppender</code> must
    be stopped in order to stop and reclaim the worker thread and to
    flush the logging events from the queue. This can be achieved by
    <a href="configuration.html#stopContext">stopping the
    LoggerContext</a> which will close all appenders, including any
    <code>AsyncAppender</code> instances. <code>AsyncAppender</code>
    will wait for the worker thread to flush up to the timeout specified
    in <span class="prop">maxFlushTime</span>. If you find that queued events
    are being discarded during close of the <code>LoggerContext</code>, you
    may need to increase the time out. Specifying a value of 0 for 
    <span class="prop">maxFlushTime</span> will force the <code>AsyncAppender</code>
    to wait for all queued events to be flushed before returning from 
   	the stop method.
    </p>
    
    <p><span class="label">Post shutdown cleanup</span>
    Depending on the mode of JVM shutdown, the worker thread processing the 
    queued events can be interrupted causing events to be strandeds in the
    queue. This generally occurs when the <code>LoggerContext</code> is not
    stopped cleanly or when the JVM terminates outside of the typical control
    flow. In order to avoid interrupting the worker thread under these 
    conditions, a shutdown hook can be inserted to the JVM runtime that 
    <a href="configuration.html#stopContext">stops the LoggerContext properly</a>
    after JVM shutdown has been initiated. A shutdown hook may also be the
    preferred method for cleanly shutting down Logback when other shutdown hooks
    attempt to log events.
    </p>


    <p>Here is the list of properties admitted by
    <code>AsyncAppender:</code></p>

		<table class="bodyTable striped">
      <tr>
        <th>Property Name</th>
        <th>Type</th>
        <th>Description</th>
      </tr>
			<tr>
        <td><span class="prop" container="async">queueSize</span></td>
        <td><code>int</code></td>
        <td>The maximum capacity of the blocking queue. By default,
        <span class="prop">queueSize</span> is set to 256.
				</td>
			</tr>
      <tr>
        <td><span class="prop" container="async">discardingThreshold</span></td>
        <td><code>int</code></td>
        <td>By default, when the blocking queue has 20% capacity
        remaining, it will drop events of level TRACE, DEBUG and INFO,
        keeping only events of level WARN and ERROR. To keep all
        events, set <span class="prop">discardingThreshold</span> to
        0.
			</td>
			</tr>
      <tr>
        <td><span class="prop" container="async">includeCallerData</span></td>
        <td><code>boolean</code></td>
        <td>Extracting caller data can be rather expensive. To improve
        performance, by default, caller data associated with an event
        is not extracted when the event added to the event queue. By
        default, only "cheap" data like the thread name and the <a
        href="mdc.html">MDC</a> are copied. You can direct this
        appender to include caller data by setting the <span
        class="prop">includeCallerData</span> property to true.
        </td>
      </tr>
      <tr>
        <td><span class="prop" container="async">maxFlushTime</span></td>
        <td><code>int</code></td>
        <td>Depending on the queue depth and latency to the referenced appender,
        the <code>AsyncAppender</code> may take an unacceptable amount of
        time to fully flush the queue. When the <code>LoggerContext</code> is 
        stopped, the <code>AsyncAppender stop</code> method waits 
        up to this timeout for the worker thread to complete. Use 
        <span class="prop">maxFlushTime</span> to specify a maximum queue flush
        timeout in milliseconds. Events that cannot be processed within this
        window are discarded. Semantics of this value are identical to that of 
        <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join(long)">Thread.join(long)</a>.
        </td>
      </tr>
      <tr>
        <td><span class="prop" container="async">neverBlock</span></td>
        <td><code>boolean</code></td>
        <td>If <code>false</code> (the default) the appender will block on
        appending to a full queue rather than losing the message. Set to
        <code>true</code> and the appender will just drop the message and
        will not block your application.</td>
      </tr>
    </table>

    <p>By default, event queue is configured with a maximum capacity
    of 256 events.  If the queue is filled up, then application
    threads are blocked from logging new events until the worker
    thread has had a chance to dispatch one or more events. When the
    queue is no longer at its maximum capacity, application threads
    are able to start logging events once again. Asynchronous logging
    therefore becomes pseudo-synchronous when the appender is
    operating at or near the capacity of its event buffer. This is not
    necessarily a bad thing. The appender is designed to allow the
    application to keep on running, albeit taking slightly more time
    to log events until the pressure on the appenders buffer eases.
    </p>

    <p>Optimally tuning the size of the appenders event queue for
    maximum application throughput depends upon several factors. Any
    or all of the following factors are likely to cause
    pseudo-synchronous behavior to be exhibited:</p>
  
    <ul>
      <li>Large numbers of application threads</li>
      <li>Large numbers of logging events per application call</li>
      <li>Large amounts of data per logging event</li>
      <li>High latency of child appenders</li>
    </ul>

    <p>To keep things moving, increasing the size of the queue will
    generally help, at the expense of heap available to the
    application.
    </p>

    
    <p><span class="label notice">Lossy behavior</span> In light of
    the discussion above and in order to reduce blocking, by default,
    when less than 20% of the queue capacity remains,
    <code>AsyncAppender</code> will drop events of level TRACE, DEBUG
    and INFO keeping only events of level WARN and ERROR. This
    strategy ensures non-blocking handling of logging events (hence
    excellent performance) at the cost loosing events of level TRACE,
    DEBUG and INFO when the queue has less than 20% capacity. Event
    loss can be prevented by setting the <span
    class="prop">discardingThreshold</span> property to 0 (zero).
    </p>

    <p class="example">Example: <code>AsyncAppender</code>
    configuration
    (logback-examples/src/main/resources/chapters/appenders/conc/logback-async.xml)</p>

    <pre id="asyncAppender" class="prettyprint source">&lt;configuration>
  &lt;appender name="<b>FILE</b>" class="ch.qos.logback.core.FileAppender">
    &lt;file>myapp.log&lt;/file>
    &lt;encoder>
      &lt;pattern>%logger{35} - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>

  <b>&lt;appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender"></b>
    <b>&lt;appender-ref ref="FILE" /></b>
  <b>&lt;/appender></b>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="<b>ASYNC</b>" />
  &lt;/root>
&lt;/configuration></pre>
  

		<h3 class="doAnchor" name="WriteYourOwnAppender">Writing your own
		Appender</h3>


    <p>You can easily write your appender by subclassing
    <code>AppenderBase</code>.  It handles support for filters, status
    messages and other functionality shared by most appenders.  The
    derived class only needs to implement one method, namely
    <code>append(Object eventObject)</code>.
    </p>

    <p>The <code>CountingConsoleAppender</code>, which we list next,
    appends a limited number of incoming events on the console. It
    shuts down after the limit is reached.  It uses a
    <code>PatternLayoutEncoder</code> to format the events and accepts
    a parameter named <code>limit</code>. Therefore, a few more
    methods beyond <code>append(Object eventObject)</code> are
    needed. As shown below, these parameters are handles
    auto-magically by logback's various configuration mechanisms.
    </p>
    
    <em>Example 4.<span class="autoExec"/>:
    <code>CountingConsoleAppender</code>
    (logback-examples/src/main/java/chapters/appenders/CountingConsoleAppender.java)</em>
    <pre class="prettyprint source">package chapters.appenders;

import java.io.IOException;

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;


public class CountingConsoleAppender extends AppenderBase&lt;ILoggingEvent> {
  static int DEFAULT_LIMIT = 10;
  int counter = 0;
  int limit = DEFAULT_LIMIT;
  
  PatternLayoutEncoder encoder;
  
  public void setLimit(int limit) {
    this.limit = limit;
  }

  public int getLimit() {
    return limit;
  }
  
  @Override
  public void start() {
    if (this.encoder == null) {
      addError("No encoder set for the appender named ["+ name +"].");
      return;
    }
    
    try {
      encoder.init(System.out);
    } catch (IOException e) {
    }
    super.start();
  }

  public void append(ILoggingEvent event) {
    if (counter >= limit) {
      return;
    }
    // output the events as formatted by our layout
    try {
      this.encoder.doEncode(event);
    } catch (IOException e) {
    }

    // prepare for next event
    counter++;
  }

  public PatternLayoutEncoder getEncoder() {
    return encoder;
  }

  public void setEncoder(PatternLayoutEncoder encoder) {
    this.encoder = encoder;
  }
}</pre>

		<p>The <code>start()</code> method checks for the presence of a
		<code>PatternLayoutEncoder</code>.  In case the encoder is not
		set, the appender fails to start and emits an error message.
		</p>
		
		<p>This custom appender illustrates two points:</p>
		
		<ul>

      <li>All properties that follow the setter/getter JavaBeans
      conventions are handled transparently by logback
      configurators. The <code>start()</code> method, which is called
      automatically during logback configuration, has the
      responsibility of verifying that the various properties of the
      appender are set and are coherent.
			</li>

			<li>The <code>AppenderBase.doAppend()</code> method invokes the
			append() method of its derived classes.  Actual output
			operations occur in the <code>append</code>() method.  In
			particular, it is in this method that appenders format events by
			invoking their layouts.
			</li>
		</ul>
		
		<p>The <a
		href="../xref/chapters/appenders/CountingConsoleAppender.html"><code>CountingConsoleAppender</code></a>
		can be configured like any other appender.  See sample
		configuration file
		<em>logback-examples/src/main/resources/chapters/appenders/countingConsole.xml</em>
		for an example.
		</p>
  

		<h2 class="doAnchor" name="logback_access">Logback Access</h2>
		
		<p>Most of the appenders found in logback-classic have their
		equivalent in logback-access. These work essentially in the same
		way as their logback-classic counterparts. In the next section, we
		will cover their use.
		</p>
		
		<h3 class="doAnchor" name="AccessSocketAppender">SocketAppender
		and SSLSocketAppender</h3>
		
		<p>The <a
		href="../xref/ch/qos/logback/access/net/SocketAppender.html">
		<code>SocketAppender</code></a> is designed to log to a remote
		entity by transmitting serialized <code>AccessEvent</code> objects
		over the wire.  Remote logging is non-intrusive as far as the
		access event is concerned.  On the receiving end after
		deserialization, the event can be logged as if it were generated
		locally.
		</p>
		
		<p>The <a href="../xref/ch/qos/logback/access/net/SSLSocketAppender.html">
    <code>SSLSocketAppender</code></a> extends the basic 
    <code>SocketAppender</code> allowing logging to a remote entity over
    the Secure Sockets Layer (SSL).
    </p>
    
		<p>
			The properties of access' <code>SocketAppender</code> are the same as those available
			for classic's <code>SocketAppender</code>.
		</p>

    <h3 class="doAnchor"
    name="AccessServerSocketAppender">ServerSocketAppender and
    SSLServerSocketAppender</h3>
    
    <p>Like <code>SocketAppender</code>, the <a
    href="../xref/ch/qos/logback/access/net/server/ServerSocketAppender.html">
    <code>ServerSocketAppender</code></a> is designed to log to a remote
    entity by transmitting serialized <code>AccessEvent</code> objects
    over the wire.  However, when using <code>ServerSocketAppender</code>
    the appender acts as a server, passively listening on a TCP socket awaiting
    inbound connections from interested clients.  Logging events delivered
    to the appender are distributed to all connected clients.
    </p>
    
    <p>The <a href="../xref/ch/qos/logback/access/net/server/SSLServerSocketAppender.html">
    <code>SSLSocketAppender</code></a> extends the basic 
    <code>ServerSocketAppender</code> allowing logging to a remote entity
    over the Secure Sockets Layer (SSL).
    </p>
    
    <p>The properties of access' <code>ServerSocketAppender</code> are
    the same as those available for classic's
    <code>ServerSocketAppender</code>.
    </p>
    
	 	
		<h3 class="doAnchor" name="AccessSMTPAppender">SMTPAppender</h3>
		
		<p>Access' <a
		href="../xref/ch/qos/logback/access/net/SMTPAppender.html">
		<code>SMTPAppender</code></a> works in the same way as its Classic
		counterpart.  However, the <span class="prop">evaluator</span>
		option is rather different.  By default, a
		<code>URLEvaluator</code> object is used by
		<code>SMTPAppender</code>. This evaluator contains a list of URLs
		that are checked against the current request's URL. When one of
		the pages given to the <code>URLEvaluator</code> is requested,
		<code>SMTPAppender</code> sends an email.
		</p>
		
		<p>
			Here is a sample configuration of a <code>SMTPAppender</code> in the access environment.
		</p>
    <p class="example">Example: <code>SMTPAppender</code>
    configuration
    (logback-examples/src/main/resources/chapters/appenders/conf/access/logback-smtp.xml)</p>

<pre class="prettyprint source">&lt;appender name="SMTP"
  class="ch.qos.logback.access.net.SMTPAppender">
  &lt;layout class="ch.qos.logback.access.html.HTMLLayout">
    &lt;pattern>%h%l%u%t%r%s%b&lt;/pattern>
  &lt;/layout>
    
  <b>&lt;Evaluator class="ch.qos.logback.access.net.URLEvaluator">
    &lt;URL>url1.jsp&lt;/URL>
    &lt;URL>directory/url2.html&lt;/URL>
  &lt;/Evaluator></b>
  &lt;from>sender_email@host.com&lt;/from>
  &lt;smtpHost>mail.domain.com&lt;/smtpHost>
  &lt;to>recipient_email@host.com&lt;/to>
&lt;/appender></pre>

		<p>This way of triggering the email lets users select pages that
		are important steps in a specific process, for example.  When such
		a page is accessed, the email is sent with the pages that were
		accessed previously, and any information the user wants to be
		included in the email.
		</p>

		<h3 class="doAnchor" name="AccessDBAppender">DBAppender</h3>
		
		<p><a
		href="../xref/ch/qos/logback/access/db/DBAppender.html"><code>DBAppender</code></a>
		is used to insert the access events into a database.
		</p>

		<p>Two tables are used by <code>DBAppender</code>:
		<em>access_event</em> and <em>access_event_header</em>. They both
		must exist before <code>DBAppender</code> can be used. Logback
		ships with SQL scripts that will create the tables.  They can be
		found in the
		<em>logback-access/src/main/java/ch/qos/logback/access/db/script</em>
		directory. There is a specific script for each of the most popular
		database systems.  If the script for your particular type of
		database system is missing, it should be quite easy to write one,
		taking as example one of the existing scripts. You are encouraged
		to contribute such missing scripts back to the project.
		</p>
		
		<p>The <em>access_event</em> table's fields are described below:</p>

		<table class="bodyTable striped">
			<tr>
				<th>Field</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td><b>timestamp</b></td>
				<td><code>big int</code></td>
				<td>The timestamp that was valid at the access event's creation.</td>
			</tr>
			<tr>
				<td><b>requestURI</b></td>
				<td><code>varchar</code></td>
				<td>The URI that was requested.</td>
			</tr>
			<tr>
				<td><b>requestURL</b></td>
				<td><code>varchar</code></td>
				<td>The URL that was requested. This is a string composed of the request method,
				the request URI and the request protocol.
				</td>
			</tr>
			<tr>
				<td><b>remoteHost</b></td>
				<td><code>varchar</code></td>
				<td>The name of the remote host.</td>
			</tr>
			<tr>
				<td><b>remoteUser</b></td>
				<td><code>varchar</code></td>
				<td>
					The name of the remote user.
				</td>
			</tr>
			<tr>
				<td><b>remoteAddr</b></td>
				<td><code>varchar</code></td>
				<td>The remote IP address.</td>
			</tr>
			<tr>
				<td><b>protocol</b></td>
				<td><code>varchar</code></td>
				<td>The request protocol, like <em>HTTP</em> or <em>HTTPS</em>.</td>
			</tr>
			<tr>
				<td><b>method</b></td>
				<td><code>varchar</code></td>
				<td>The request method, usually <em>GET</em> or <em>POST</em>.</td>
			</tr>
			<tr>
				<td><b>serverName</b></td>
				<td><code>varchar</code></td>
				<td>The name of the server that issued the request.</td>
			</tr>
			<tr>
				<td><b>event_id</b></td>
				<td><code>int</code></td>
				<td>The database id of the access event.</td>
			</tr>
		</table>
		
		<p>
			The <em>access_event_header</em> table contains the header of each
			request. The information is organised as shown below:
		</p>

		<table class="bodyTable striped">
			<tr>
				<th>Field</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td><b>event_id</b></td>
				<td><code>int</code></td>
				<td>The database id of the corresponding access event.</td>
			</tr>
			<tr>
				<td><b>header_key</b></td>
				<td><code>varchar</code></td>
				<td>The header name, for example <em>User-Agent</em>.</td>
			</tr>
			<tr>
				<td><b>header_value</b></td>
				<td><code>varchar</code></td>
				<td>The header value, for example <em>Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) Gecko/20061010 Firefox/2.0</em></td>
			</tr>
			</table>

		<p>All properties of classic's <code>DBAppender</code> are available
			in access's <code>DBAppender</code>. The latter offers one more option,
			described below.
		</p>
		
		<table class="bodyTable striped">
			<tr>
				<th>Property Name</th>
				<th>Type</th>
				<th>Description</th>
			</tr>
			<tr>
				<td>
					<b>
						<span class="prop">insertHeaders</span>
					</b>
				</td>
				<td>
					<code>boolean</code>
				</td>
				<td>
					Tells the <code>DBAppender</code> to populate the database with the header
					information of all incoming requests.
				</td>
			</tr>
		</table>

		<p>Here is a sample configuration that uses <code>DBAppender</code>.</p>

    <p class="example">Example: DBAppender configuration <em>(logback-examples/src/main/resources/chapters/appenders/conf/access/logback-DB.xml)</em></p>
    
    <pre class="prettyprint source">&lt;configuration>

  &lt;appender name="DB" class="ch.qos.logback.access.db.DBAppender">
    &lt;connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
      &lt;driverClass>com.mysql.jdbc.Driver&lt;/driverClass>
      &lt;url>jdbc:mysql://localhost:3306/logbackdb&lt;/url>
      &lt;user>logback&lt;/user>
      &lt;password>logback&lt;/password>
    &lt;/connectionSource>
    &lt;insertHeaders>true&lt;/insertHeaders>
  &lt;/appender>

  &lt;appender-ref ref="DB" />
&lt;/configuration></pre>


    <h3 class="doAnchor"
    name="AccessSiftingAppender">SiftingAppender</h3>
   
    <p>The SiftingAppender in logback-access is quite similar to its
    logback-classic counterpart. The main difference is that in
    logback-access the default discriminator, namely <a
    href="../xref/ch/qos/logback/access/sift/AccessEventDiscriminator.html">AccessEventDiscriminator</a>,
    is not MDC based. As its name suggests, AccessEventDiscriminator,
    uses a designated field in AccessEvent as the basis for selecting a
    nested appender. If the value of the designated field is null,
    then the value specified in the <span
    class="prop">defaultValue</span> property is used.
    </p>

    <p>The designated AccessEvent field can be one of COOKIE,
    REQUEST_ATTRIBUTE, SESSION_ATTRIBUTE, REMOTE_ADDRESS, LOCAL_PORT,
    REQUEST_URI. Note that the first three fields require that the
    <span class="prop">AdditionalKey</span> property also be
    specified.</p>
    
    <p>Below is an example configuration file.</p>

    <p class="example">Example: SiftingAppender configuration (logback-examples/src/main/resources/chapters/appenders/conf/sift/access-siftingFile.xml)</p>
    
    <pre class="prettyprint source">&lt;configuration>
  &lt;appender name="SIFTING" class="ch.qos.logback.access.sift.SiftingAppender">
    &lt;Discriminator class="ch.qos.logback.access.sift.AccessEventDiscriminator">
      &lt;Key>id&lt;/Key>
      &lt;FieldName>SESSION_ATTRIBUTE&lt;/FieldName>
      &lt;AdditionalKey>username&lt;/AdditionalKey>
      &lt;defaultValue>NA&lt;/defaultValue>
    &lt;/Discriminator>
    &lt;sift>
       &lt;appender name="${id}" class="ch.qos.logback.core.FileAppender">
        &lt;file>byUser/${id}.log&lt;/file>
        &lt;layout class="ch.qos.logback.access.PatternLayout">
          &lt;pattern>%h %l %u %t \"%r\" %s %b&lt;/pattern>
        &lt;/layout>
      &lt;/appender>
    &lt;/sift>
  &lt;/appender>
  &lt;appender-ref ref="SIFTING" />
&lt;/configuration></pre>


    <p>In the above configuration file, a <code>SiftingAppender</code>
    nests <code>FileAppender</code> instances. The key "id" is
    designated as a variable which will be available to the nested
    <code>FileAppender</code> instances. The default discriminator,
    namely <code>AccessEventDiscriminator</code>, will search for a
    "username" session attribute in each <code>AccessEvent</code>. If
    no such attribute is available, then the default value "NA" will
    be used.  Thus, assuming the session attribute named "username"
    contains the username of each logged on user, there will be a log
    file under the <em>byUser/</em> folder (of the current folder)
    named after each user containing the access logs for that user.
    </p>


    <script src="../templates/footer.js" type="text/javascript"></script>


  </div>
</div>  
</body>
</html>
